Javascript

Top 7 Javascript Array Functions You Should Know Filter, Find, Map, and More

Top 7 Javascript Array Functions You Should Know Filter, Find, Map, and More

There are numerous javascript functions for manipulating arrays, in this article i will describe some important javascript array functions used in web applications for everyday tasks.

 

 

1. Filter

The filter() function is mostly used in javascript to filter arrays. This function accepts a callback which determines which element to return in the filtered array according to specific condition. Then it return the filtered elements in a new array.

The terminology of this function as follows:

filter(function callbackFn(element) {  })
filter(function callbackFn(element, index) {  })

Using arrow function:

filter((element) => {  } )
filter((element, index) => {  } )

Using callback name:

filter(callbackFn)

The callback function takes at least one parameter which is the current item and two optional parameters which represent the index and the array being traversed.

Let’s see an example where we have an array of numbers and we want to filter this array to return the even numbers only:

<script>
   	   var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
   	   var filteredArrays = numbers.filter(item => item % 2 == 0);

   	   console.log(filteredArrays);
</script>

// Array (6) [0, 2, 4, 6, 8, 10]

As shown here the callback passed to the filter function is an arrow function that checks if the remainder of the item when divided by 2 equal zero. the result as an array of the filtered numbers.

The filter function also is used when filtering collections of objects like this example:

<script>
   const programmingTools = [
            {
            	id: 1,
            	title: 'PHP'
            },
            {
            	id: 2,
            	title: 'C#'
            },
            {
            	id: 3,
            	title: 'Javascript'
            },
            {
            	id: 4,
            	title: 'Reactjs'
            }
       ];

       const filterCallback = (item) => item.id == 3 || item.id == 4;    // filter callback
       const clientTools = programmingTools.filter(filterCallback);
       console.log(clientTools);
</script>

You can also filter using the item index so in the previous example let’s rewrite the filter function to filter only the first item:

const filterCallback = (item, index) => index == 0;
const firstItem = programmingTools.filter(filterCallback);
console.log(firstItem);

The most great aspect of the filter function is immutability which means it doesn’t modify the original array.

 

2. Map

The map() function invoke a callback in every element in an array. The callback passed has the same parameters we saw above using the filter() function. You can think of map as a for loop because it returns a new array after applying the provided callback in each element.

In this example we use map() to multiply each element in array by 2:

<script>
   const numbers = [1, 2, 3, 4];
   const mapped = numbers.map(i => i * 2);

   console.log(mapped);
</script>

// (4) [2, 4, 6, 8]

Also we can use map() to retrieve a list of ids in collection of objects, let’s rewrite the previous collection example as shown:

const programmingTools = [
            {
            	id: 1,
            	title: 'PHP'
            },
            {
            	id: 2,
            	title: 'C#'
            },
            {
            	id: 3,
            	title: 'Javascript'
            },
            {
            	id: 4,
            	title: 'Reactjs'
            }
       ];

       const idsCallback = function (item) {
           return item.id;
       }

       const ids = programmingTools.map(idsCallback);

       console.log(ids);


// (4) [1, 2, 3, 4]

 

3. ForEach

The forEach() function similar to map(), it invoke a callback on each item of array, but the major difference is the return value. map() return the newly transformed array after applying the callback on each item, but the forEach() return undefined.

 forEach() is very much like traditional for loop, in just it iterates over an array and calls the callback on each item only without storing the result back into variable.

Let’s see this example we saw earlier with map() but now using forEach:

var numbers = [1, 2, 3, 4];
  var returnedVal = numbers.forEach(i => {
  console.log(i * 2);
});

console.log("returned value: ", returnedVal);

// output
// 2
// 4
// 6
// 8
// returned value:  undefined

 

4. Find

The find() function search for the first element in an array if the element satisfies the provided callback function. The callback have the same parameters like the above functions. If a match is found in the array it return that element, otherwise it returns undefined.

The find() function act as a for loop when searching for a particular item in an array.

Example searching for a specific country in array:

const countries = ["USA", "Canada", "UK"];

const searchItem = countries.find(name => name == "Canada");

console.log(searchItem != undefined ? searchItem : "no match found");

// Canada

In the same way we can use find() when working with collections:

const programmingTools = [
            {
            	id: 1,
            	title: 'PHP'
            },
            {
            	id: 2,
            	title: 'C#'
            },
            {
            	id: 3,
            	title: 'Javascript'
            },
            {
            	id: 4,
            	title: 'Reactjs'
            }
       ];

      

const searchItem = programmingTools.find(item => item.id == 3);

console.log(searchItem);

// {id: 3, title: "Javascript"}

 

5. FindIndex

The findIndex() function works like the previous find() function but instead of returning the first matched element it returns the index of the element, if no match found it returns -1.

For example let’s rewrite the previous example to search the country using index like so:

const countries = ["USA", "Canada", "UK"];

const searchIndex = countries.findIndex(name => name == "Canada");

if(searchIndex !== -1) {
   console.log("Item index:", searchIndex);
   console.log("Searched item:", countries[searchIndex]);
} else {
   console.log("no match found");
}

// Item index: 1
// Searched item: Canada

 

6. Reduce

The reduce() function is one of the more advanced and powerful function in javascript. The terminology of this function as follows:

reduce(callbackFn)
reduce(callbackFn, initialValue)

With arrow function:

reduce((accumulator, currentValue) => { ... } )
reduce((accumulator, currentValue, index) => { ... } )
reduce((accumulator, currentValue, index) => { ... }, initialValue)

The reduce() function accepts a reducer function as the first argument and an optional parameter which is the initial value. But what is a reducer function, the reducer is a common paradigm in many programming language. The reducer iterate an array and return a single value, this in contrast with map() for example which return the same array modified.

Let’s imagine an example where we have an array of numbers and we want to sum all the values, so we can use a simple for loop to do this but reduce() can also be used for this purpose as shown:

var numbers = [0, 1, 2, 3, 4];
var sum = numbers.reduce((accumulator, currentVal) => {
    return accumulator + currentVal;
});

console.log("sum: ", sum);

// output
// sum:  10

As you see the reducer return the result of the sum operation as a single value, but let’s see how the reducer function works.

The reducer function accepts these parameters:

  • accumulator (required)
  • current value (required)
  • current index (optional)
  • source array (optional)

The accumulator accumulates return values which means in every iteration the result of the last iteration will be remembered and appended from the current value. Like in this example the accumulator is incremented by the current value in each iteration.

The current value and current index represent the current value and current index from the current iteration respectively.

There are some points you need to be aware about when using the reducer function, let’s understand it in the context of the previous example:

  1. First Scenario: when the initial value is not present in reduce() function:

   – When there is no initial value passed to reduce() then in the first iteration the accumulator will equal to the first value in the array and the current value will be the second value in the array, in other terms the callback will be executed starting at index 1 not 0. So in the previous example it actually starts from element 1.

-If the array is empty a TypeError will be thrown.

 2. Second Scenario: when the initial value is present in reduce() function:

-When the initial value passed to reduce() then in the first iteration the accumulator will equal to the initial value and the current value will equal to the first element in the array.

 

Now modify the previous example by supplying an initial value of 20:

// the accumulator will start with 20

var numbers = [0, 1, 2, 3, 4];
   var sum = numbers.reduce((accumlator, currentVal) => {
   return accumlator + currentVal;
}, 20);

console.log("sum: ", sum);

// output
// 30

Check out this diagram to see the difference when passing the initial value and without the initial value.

describing javascript reduce function

Example 1: concatenate an array of strings:

const strings = ["javascript", "reducers", "is", "awesome"];

const statement = strings.reduce((accumlator, currentVal) => {
   return accumlator + " " + currentVal;
});

console.log(statement);

// output
// javascript reducers is awesome

Example 2: sum all values in array of objects:

const categories = [
            {
               name: 'clothes',
               count: 120
            },
            {
               name: 'televisions',
               count: 200
            },
            {
               name: 'mobiles',
               count: 70
            }
         ];

         let initialVal = 0;

         const totalProducts = categories.reduce(function (accumlator, currentVal)  {
            return accumlator + currentVal.count;
         }, initialVal);

         console.log("Total products: ", totalProducts);

// output
// Total products:  390

Example 3: transform multidimensional array into single dimensional array:

const menu_dishes = [["meat", "chicken"], ["potatos", "bean"], ["fruit salad", "vegetable salad"]];

         const reducer = function(acc, current) {
            return acc.concat(current);
         };

         const all_dishes = menu_dishes.reduce(reducer);

         console.log("all dishes: ", all_dishes);

// output
// (6) ["meat", "chicken", "potatos", "bean", "fruit salad", "vegetable salad"]

 

7. Fill

The last function i will about is the fill() function, this function is simple and used to fill an array with static value you specify from start to end index. The function takes three parameters:

  • value: represent the value you fill with. This is required.
  •  start: represent the start index, this is optional parameter which defaults to 0.
  • end: represent the end index, this is optional parameter which if omitted represent arr.length.

Example 1: Passing value only

var numbers = [0, 1, 2, 3, 4];
var modified_numbers = numbers.fill(7);

 console.log("modified_numbers: ", modified_numbers);

// output
// modified_numbers:  (5) [7, 7, 7, 7, 7]

Example 2: Passing start index

var modified_numbers = numbers.fill(7, 2);

console.log("modified_numbers: ", modified_numbers);

// output
// modified_numbers:  (5) [0, 1, 7, 7, 7]

Example 3: Passing start and end index

var modified_numbers = numbers.fill(7, 2, 4);

console.log("modified_numbers: ", modified_numbers);

// output
// modified_numbers:  (5) [0, 1, 7, 7, 4]

Example 4: Passing negative start index 

var modified_numbers = numbers.fill(7, -2);

console.log("modified_numbers: ", modified_numbers);

// output
// modified_numbers:  (5) [0, 1, 2, 7, 7]

Using negative start index will change the start index to be arr.length + start. In the same way using negative end index will change end index to be arr.length + end.

 

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments