Arrays in Javascript

Date: 19/02/2020

Introduction

Array in Javascript has some of the in-built methods that are very much handy when manipulating the array contents than whatever operation you can do with forEach or for a loop. If you know how to handle those in-built methods, you can tackle some of the complex logic without complex implementations. I do use them in everyday work. In this tutorial, though I will not all of those in-built methods, will explain the most useful methods.

Map

Array.prototype.map(currentValue, index, array)

let 1dArrray = [1, 2,  3, 4]

let 2dArray = 1dArray.map((currentValue) => {
    return [currentValue, currentValue]
});

console.log(2dArray) // [ [1, 1], [ 2, 2], [3, 3], [4, 4] ]

What happens behind is that no matter what work you do inside the parenthesis it will replace the currentValue with the value you return eventually. If you don’t ‘undefined’ will be there. In other words, the transformation will happen with a current array value.

Note: it will array with same size

Filter

Array.prototype.filter(currentValue, index, array)

let oddEven = [1, 2,  3, 4]
let even = oddEven.map((currentValue) => {
    return currentValue % 2 == 0
});
console.log(even) // [ 2, 4]

In this filter case, the difference with a map is it will return array value that satisfies the return statement inside the parenthesis.

Note: it may or may not array with the same size depending on what you do. but the returned array will be a new array.

Reduce:

Array.prototype.reduce((prev, next),initialValue)

let ones = [1, 1, 1, 1, 1, 1]
let sum = ones.reduce((prev, next) => {
  return prev + next;
}, 100)

console.log(sum)  // 106

The reduce function is very different from the map or filter. It will one return a Number for your array of numbers. If you didn’t mention initial value, it will take the array value at index 0 as the initial value and index at 1 as the next value for the first iteration. If there is no next value, then iteration will stop as know.

You can also check out slice, reduceRight, and others too.

Note: splice considered an impure function. To know more about what is pure or not check here https://www.freecodecamp.org/news/what-is-a-pure-function-in-javascript-acb887375dfe/

For more interesting concepts in javascript, check the below.
https://javascript.info/

Conclusion

Thanks for you. If you found it useful share it with others to keep it afloat.

1 thought on “Arrays in Javascript”

Leave a Reply