Arrays are the bread and butter of javascript when it comes to handling data. Especially awhen grabbing data from APIs and filtering results. I’ve noted some super useful built in methods relating to arrays, to help with all sorts of situations. Get to know these, for great power comes great responsibility…
Filtering an array
Array.prototype.filter()
This will loop through an existing array and returns a brand new one based on the conditions you provide:
const filteredMisters = array.filter(item => {
return item.suffix === 'Mr';
})
console.log(filteredMisters)
// returns new array of items where item.suffix value is 'Mr'
Sorting array items
Array.prototype.sort()
This just does as described, though to be honest it can be tricky to get your head around the logic behind it. If no function is defined as a parameter, it will just sort an array alphabetically. Otherwise in order to facilitate sorting further, you need to give it two values to compare.
const names = ["Bob", "Jeff", "Harry", "Kim];
names.sort((name1, name2) =>
{
return name1 > name2? 1: -1
}
);
// this returns the array ["Bob", "Harry", "Jeff", "Kim"]
Now to explain what’s going on here…you ready?
Think of this almost behaving as a looping function, it’s quickly running a sort for every item in the array. i.e:
Is Bob (name1) greater (alphabetically) than Jeff? No, then lower the index position of Bob. Bob goes before Jeff (return -1).
Is Jeff (name2) greater than Harry? Yes, then increase the index position of Jeff (return 1).
etc etc…
Note that if two values are the same, then 0 will be returned and neither value gets moved.
Creating a new array from an array
Array.prototype.map()
Sometimes you’ll want to create a new array from an existing one, for example when you need only specific values, especially useful with an array of objects with key value pairs. When using arrays in javascript, I find this array method to be the most useful.
const users = [
{name: "Jim", age: 22, id:1},
{name: "Adam", age: 25, id:2},
]
const userNames = users.map(user => user.name);
// returns the array: ["Jim", "Adam"]
// user refers to each item in the array
// user.name refers to the new value for the item in the array
// another example, but changing the key values...
// brackets () are required to not confuse it with the functions // curly braces
const firstNames = users.map(user => ({firstname:user.name}))
//returns [{firstname: "Jim"}, {firstname: "Adam"}]
Returning the sum of array items
Array.prototype.reduce()
This is especially useful if you want to tally up/remove duplicate entries in an array.
const carData = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck', 'pogostick'];
const transportation = carData.reduce(function(obj, item) {
if (!obj[item]) {
obj[item] = 0;
// for each new vehicle type you come across, you'll need this
// to be set, or else it will return undefined
}
obj[item]++;
return obj;
}, {});
// these optional end brackets are for the initial value, which // is an empty object where the recurring values are stored.
// returns
// {"car": 5,"truck": 3,"bike": 2,"walk": 2,"van": 2,
// "pogostick": 1}
An alternative, and more performant approach to filtering out duplicates in an array would be to use Set
as follows:
const carData = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck', 'pogostick'];
arrayNoDupes = Array.from(new Set(carData))
// returns [
"car",
"truck",
"bike",
"walk",
"van",
"pogostick"
]
Check if at least one array item of a defined value exists
Array.prototype.some()
This checks through an array to see if at least one of a defined value exists. Returns a boolean value.
const people = [
{name: "Joe", age: 19},
{name: "Fred", age: 17},
{name: "Ted", age: 21}
];
const isAdult = people.some(person => (person.age >= 19);
// will return true
Check if all array items have a specific value
A value must exist in all array items or else it will return false. Returns a boolean value.
const people = [
{name: "Joe", age: 19},
{name: "Fred", age: 17},
{name: "Ted", age: 21}
];
const allAdults = people.every(person => (person.age >= 19));
// returns false
Returning a unique value
Array.prototype.find()
Similar to filter, but just returns one value, e.g:
const people = [
{name: "Joe", id: 1},
{name: "Fred", id: 2},
{name: "Ted", id: 3}
];
const onePerson = people.find(person => (person.id === 1));
// returns {name: "Joe", id: 1}
Returning the index position of a unique value
Array.prototype.findIndex()
Similar to find, but will return the index position of the value within the array.
const people = [
{name: "Joe", id: 1},
{name: "Fred", id: 2},
{name: "Ted", id: 3}
];
const onePerson = people.find(person => (person.id === 3));
// returns 2, (following the index 0:Joe, 1:Fred, 2:Ted)
Useful extras with arrays
The spread operator
Using these three dots will essentially unwrap it from it’s parent array. Useful for concatenating multiple arrays.
const array1 = ["i", "am", "array 1."];
const array2 = ["i", "am", "array 2."];
const arrayConcat = [...array1,...array2, "all three", "arrays!"];
// returns ["i", "am", "array 1.", "i", "am", "array 2.", "all three", "arrays!"];
Changing the value of multiple variables
A handy shortcut for when you need to change the value of multiple variables in one hit.
let name = "phil";
let age = 23;
[name, age] = ["bill", 35];
console.log(name, age);
// returns "bill", 35
Returning a list of elements on a page
When you need to grab a list of elements on a page, you may think it returns an array, but it’s actually a NodeList
. This is more limited in terms of available methods, so you may want to convert it into an array:
const images = document.querySelectorAll("img");
const sources = Array.from(images, (image) => image.src);
This will allow you to use extra array methods such as sort, etc. The function will also allow you to pick out the exact data you need, prior to creating the array.
Front end developers will find themselves using arrays in Javascript a lot, so I’ve found this knowledge to be especially useful. I’d argue the methods above could even be considered essential web tools for web development.