Arrays are omnipresent in JavaScript but some powerful methods are not used as much as they should be. In this article, we're looking at 3 that will help you solve problems faster.

Filter

Just as the name implies, we are 'filtering' the elements of an array based on a given criteria; in the example below, we're finding all even numbers in an array:

let myArray = [1, 4, 42, 11, 79];
let letters = myArray.filter((item) => {
  return (item % 2) === 0;
});
console.log(letters); // [4, 42]

Let's look at a slightly more complicated example, retrieving all string elements from an array:

let myArray = ["a", 42, 3.14];
let letters = myArray.filter((item) => {
  return Object.prototype.toString.call(item) === "[object String]";
});
console.log(letters); // ["a"]

Map

The `map` method allows us to transform each element of an array into another entity based on a certain flow. In the example below, we're calling an arrow function on each item of the array:

let myArray = [1, 4, 42, 11, 79];
let doubleArray = myArray.map((item) => {
  return item * 2;
});
console.log(doubleArray); // [2, 8, 84, 22, 158]

Notice that we're returning a new array whilst the original one remains unchanged.

One very common usecase is to return an array containing an object property:

let articles = [
  { title: 'article 1', abstract: 'abstract 1'},
  { title: 'article 2', abstract: 'abstract 2'},
  { title: 'article 3', abstract: 'abstract 3'}
];

let titles = articles.map((article) => {
  return article.title;
})
console.log(titles); // ["article 1", "article 2", "article 3"]

Reduce

The `reduce` method might look a bit confusing at first but the clue it's in the name - it reduces the entire array to one value. Let's see how to calculate the sum of all elements in an array:

let myArray = [1, 4, 42, 11, 79];
let total = myArray.reduce((item, currentTotal) => {
  return currentTotal + item;
}, 0);
console.log(total); // 137

Notice that `reduce` takes 2 parameters: an arrow function that computes the current step, and the initial value. The value returned at one step is being injected as `currentTotal` for the next step or returned when we exhausted the array.

We mentioned above that `reduce` reduces the array to one value - that's true when the array is single-dimensional. But it can also be used to flatten multi-dimensional arrays:

let myArray = [[1, 4], 23, [42, 11], 79];
const flatArray = myArray.reduce((currentFlatArray, amount) => {
  return currentFlatArray.concat(amount);
}, []);
console.log(flatArray); // [1, 4, 23, 42, 11, 79]

All together now

Let's compute the words frequency in a piece of text:

let text = 'Alice was beginning to get very tired of sitting ' +
'by her sister on the bank, and of having nothing to do : ' +
'once or twice she had peeped into the book her sister was ' +
'reading, but it had no pictures or conversations in it ... ';


// 1. Split text into words
let words = text.split(" ");

// 2. Compute word count
var wordsCount = words.reduce( (tally, word) => {
  let lowercaseWord = word.toLowerCase();
  tally[lowercaseWord] = (tally[lowercaseWord] || 0) + 1 ;
  return tally;
} , {});


// 3. Sort word count with the most used first

// 3.1. Create array from dictionary
var wordsCountArray = Object.keys(wordsCount).map(function(key) {
  return [key, wordsCount[key]];
});

// 3.2. Sort the array based on the second element
wordsCountArray.sort(function(first, second) {
  return second[1] - first[1];
});

// 4. Display the end result
console.log(wordsCountArray);

The output will show the most used words:

[["was", 2], ["to", 2], ["of", 2], ["her", 2], ["sister", 2], 
["the", 2], ["or", 2], ["had", 2], ["it", 2], ["alice", 1], 
["beginning", 1], ["get", 1], ["very", 1], ["tired", 1], 
["sitting", 1], ["by", 1], ["on", 1], ["bank,", 1], 
["and", 1], ["having", 1], ["nothing", 1], ["do", 1], 
[":", 1], ["once", 1], ["twice", 1], ["she", 1], 
["peeped", 1], ["into", 1], ["book", 1], ["reading,", 1], 
["but", 1], ["no", 1], ["pictures", 1], ["conversations", 1], 
["in", 1], ["...", 1], ["", 1]]

Next Steps