Table of contents
Open Table of contents
Intro
On the other day I was writing a function, where I needed to filter and “simplify” an array of JS objects. The logic to filter was somewhat complex, and it took some time to get it working as I wanted.
Sometimes it’s good to go back to basics, and start from simple examples and iterate from there. In this article I want to give a basic level reminder of JS array methods, for future reference.
JS Array to work with
I am going to be playing with some Azure virtual machine instance types in this example.
const instances = [
{
size: 'Standard_A1_v2',
vCore: 1,
MemoryGiB: 2,
TempStorageGiB: 10,
MaxNICs: 2,
ExpectedNetworkBandwidthMbps: 250
},
{
size: 'Standard_A2_v2',
vCore: 2,
MemoryGiB: 4,
TempStorageGiB: 20,
MaxNICs: 2,
ExpectedNetworkBandwidthMbps: 500
},
{
size: 'Standard_A4_v2',
vCore: 4,
MemoryGiB: 8,
TempStorageGiB: 40,
MaxNICs: 4,
ExpectedNetworkBandwidthMbps: 1000
},
{
size: 'Standard_A8_v2',
vCore: 8,
MemoryGiB: 16,
TempStorageGiB: 80,
MaxNICs: 8,
ExpectedNetworkBandwidthMbps: 2000
},
{
size: 'Standard_A2m_v2',
vCore: 2,
MemoryGiB: 16,
TempStorageGiB: 20,
MaxNICs: 2,
ExpectedNetworkBandwidthMbps: 500
},
{
size: 'Standard_A4m_v2',
vCore: 4,
MemoryGiB: 32,
TempStorageGiB: 40,
MaxNICs: 4,
ExpectedNetworkBandwidthMbps: 1000
},
{
size: 'Standard_A8m_v2',
vCore: 8,
MemoryGiB: 64,
TempStorageGiB: 80,
MaxNICs: 8,
ExpectedNetworkBandwidthMbps: 2000
}
];
ES6 syntax will be used in most cases.
Map
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
// List all instance sizes
const sizes = instances.map(instance => instance.size);
console.log(sizes);
// List all instance sizes and their respective vCore counts
const sizesAndVcores = instances.map(instance => ({
size: instance.size,
vCore: instance.vCore
}));
console.log(sizesAndVcores);
Reduce
The
reduce()
method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
// Given I have 1 instance of each type running,
// what is the max network bandwith I can get?
const totalBandwith = instances.reduce(
(acc2, cur) => acc2 + cur.ExpectedNetworkBandwidthMbps, 0);
console.log(`Total Network Bandwith is ${totalBandwith} Mbps`);
// List number of instances by NIC count
const instancesByNICCount = instances.reduce((acc, cur) => {
const NICCount = cur.MaxNICs.toString();
if (acc[NICCount]) {
acc[NICCount]++;
} else {
acc[NICCount] = 1;
}
return acc;
}, {});
console.log(instancesByNICCount);
Filter
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.
// Find all instances, which have more than 16 GiB of memory
const instancesOver16GiB = instances.filter(instance => instance.MemoryGiB >= 16);
console.log(instancesOver16GiB);
// Find all instances, which have more than 16 GiB of memory,
// return only sizes
const instancesOver16GiB2 = instances
.filter(instance => instance.MemoryGiB >= 16)
.map(instance => instance.size);
console.log(instancesOver16GiB2);
Sort
The
sort()
method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
// Sort instances by TempStorageGiB, ascending
const instancesByTempStorageGiBAsc = instances.sort(
(a, b) => a.TempStorageGiB - b.TempStorageGiB);
console.log(instancesByTempStorageGiBAsc);
// Sort instances by TempStorageGiB, descending
const instancesByTempStorageGiBDesc = instances.sort(
(a, b) => b.TempStorageGiB - a.TempStorageGiB);
console.log(instancesByTempStorageGiBDesc);
// Sort instances by size, alphabetically, ascending
const instancesBySizeAsc = instances.sort((a, b) => {
if (a.size < b.size) return -1;
return 1;
});
console.log(instancesBySizeAsc);
// Sort instances by size, alphabetically, descending
const instancesBySizeDesc = instances.sort((a, b) => {
if (a.size < b.size) return 1;
return -1;
});
console.log(instancesBySizeDesc);
Every
The
every()
method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
// Does every instance in our array have more than 2 vCores?
const allInstancesHaveVCoreCount2 = instances.every(instance => {
return instance.vCore >= 2;
})
console.log(allInstancesHaveVCoreCount2);
// Does every instance in our array have size defined?
const allInstancesHaveSizeDefined = instances.every(instance => {
// Check, that the key exists, and the value is not undefined
return 'size' in instance && instance.size != undefined;
})
console.log(allInstancesHaveSizeDefined);
Some
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
// Does any of our instances have 4 or more NICs available?
const anyInstancesWithMoreThan4NICs = instances.some(instance => instance.MaxNICs >= 4);
console.log(anyInstancesWithMoreThan4NICs);
There are plenty more methods for JS Arrays, these were only some quite often used ones.