Useful Javascript Array trick which one should know

Deepak Mankotia
6 min readJul 8, 2021

--

Table of content
* Iterative methods map(), every(), filter(), forEach(), some().
* Reduction Methods reduce() and reduceRight().
* Manipulation methods concat(), slice() and splice().
* Reordering methods reverse() and sort().
* push(), pop(), shift(), unshift().
* Remove duplicate element from array
* Replace specific element in array
* Map an array without using map()
* Empty an array
* Fill array with data.
* Merge two or more arrays
* Reverse an array

Array Iterative methods -

map() — method creates a new array with the results of calling a function for every array element. This does not change the original array and also does not execute for empty array.

let arr = [6, 9, 12, 15]; //array with different numbers
let newArr = arr.map(Math.sqrt); // calculate the square root of all the number in array
//output
Console.log(newArr); //[2.449489742783178, 3, 3.4641016151377544, 3.872983346207417]

every() — returns true if method returns true for all the items in array. This does not change the original array and also does not execute for empty array.

let age = [34, 36, 40, 18]; //array of age
let age_greater_than_18 = age.every(item => item > 18); //compare for all the values and return true if all the ages are greater than 18
//output
console.log(age_greater_than_18); //false
let age = [34, 36, 40, 19]; //array of age
let age_greater_than_18 = age.every(item => item > 18);
//output
console.log(age_greater_than_18); //true

filter() — returns an array of all items for which the method returns true. This does not change the original array and also does not execute for empty array.

let ages = [32, 33, 16, 40]; // array of ages
let age_18_or_over = ages.filter(age => age >= 18); //return all the ages 18 or over
//output
console.log(age_18_or_over); //[32, 33, 40]

forEach()- this run the function for every item in the array and return no value.

let fruits =  ["apple", "orange", "mango"]; //fruits array
fruits.forEach((fruit, index) => console.log(index, fruit));
//output
0 "apple"
1 "orange"
2 "mango"

some() — returns true if the function returns true for at least one of the items. This does not change the original array and also does not execute for empty array.

let age = [34, 36, 40, 18]; //array of age
let age_greater_than_18 = age.some(item => item > 18);
//output
console.log(age_greater_than_18); //true

Array Reduction Methods

reduce()- iterates the elements starting to the end of the array and returns the single value. This does not change the original array and also does not execute for empty array.

let numbers = [1,2,3,4,5,6,7,8,9];
let sum = numbers.reduce((total, currentNumber) => total + currentNumber, 0); //in this I have provided the 2nd parameter as number which is 0
//output
console.log(sum) //45
let sum = numbers.reduce((total, currentNumber) => total + currentNumber, ''); //in this I have provided the 2nd parameter as empty string, we start from '' add concatenate each value, starting from the left//output
"123456789"

reduceRight() — iterates the elements starting from the end of the array and returns the single value. This does not change the original array and also does not execute for empty array.

let numbers = [1,2,3,4,5,6,7,8,9];
let sum = numbers.reduceRight((total, currentNumber) => total + currentNumber, ''); //in this I have provided the 2nd parameter as empty string, we start from '' add concatenate each value, starting from the right
//output
"987654321"

Manipulation methods

concat() — Concat allows to concatenation / join tow or more arrays. This method concat the arrays and return the new array. Here original array is not changed the changes are made on the copy of original array.

let value1 = [1,2,3,4,5];
let value2 = [6,7,8,9,10];
let concatVal = value1.concat(value2);
//output
console.log(concatVal); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

slice() — Slice is similar to concat, it creates copy of array with the same sequence of original array. If there is no parameter it return the original array. With one argument it return the value from that index to last index of array. It can also be used with two arguments start index and end index, in this case it will return the items between that interval.

let numbers = [1,2,3,4,5];
console.log(numbers.slice());
console.log(numbers.slice(1));
console.log(numbers.slice(0,2));
//output
[1, 2, 3, 4, 5]
[2, 3, 4, 5]
[1, 2]

splice() — Splice is almost similar to concat and slice, the only difference is that it perform operation on original array, So be very careful while using this as the action once performed it won’t be reverted.

let numbers = [1,2,3,4,5];
console.log(numbers.splice(0,1,10)); //it will replace the first value with 10
//output
[10, 2, 3, 4, 5]

Array Reordering methods

reverse() — it reverse the order of the items and create the duplicate of the original array. It will not affect the original array.

let numbers = [1,2,3,4,5];
console.log(numbers.reverse());
//output
[5, 4, 3, 2, 1]

sort() — This short the elements of array by doing the string comparison. It by default convert the elements to string and then compare.
let’s understand this by below example

let numbers = [1,2,3,4,10];
console.log(numbers.sort())
//output
[1, 10, 2, 3, 4]

If you check the above example the output is in right format, right?
Don’t get confused, sort() function first change all the elements to string and then compare so in this case “10” is bigger than 2.
There is solution to sort the elements without first converting to string let’s check that

let numbers = [1,2,3,4,10];
console.log(numbers.sort((val1, val2) => val1 - val2))
//output
[1, 2, 3, 4, 10]

In above example the function takes additional parameters which replace the default string comparison behavior.

push() — It adds the element at the end of array and return the new length of the array. It made changes to the original array.

let numbers = [1,2,3,4,10];
console.log(numbers.push(11));
console.log(numbers);
//output
6
[1, 2, 3, 4, 10, 11]

pop() — It removes the last element from the array and returns the deleted element. It made changes to the original array.

let numbers = [1,2,3,4,10];
console.log(numbers.pop());
console.log(numbers);
//output
10
[1, 2, 3, 4]

shift() — It delete the first element of the array and return the deleted element. It made changes to the original array.

let numbers = [1,2,3,4,10];
console.log(numbers.shift());
console.log(numbers);
//output
1
[2, 3, 4, 10]

unsift() — it add new element at the starting of the array and return the new length of array.

let numbers = [1,2,3,4,10];
console.log(numbers.unshift(0));
console.log(numbers);
//output
6
[0, 1, 2, 3, 4, 10]

Remove duplicate element from array

How to extract unique values from an Javascript array, let’s try to find the solution with below example.

let fruits = ["banana", "mango", "grapes", "orange", "mango"];method 1 - console.log(Array.from(new Set(fruits)));
method 2 - console.log([...new Set(fruits)]);
Output 1 - ["banana", "mango", "grapes", "orange"]
Output 2 - ["banana", "mango", "grapes", "orange"]

In above example I use new Set() to extract the unique values also I use 2 different ways to do the same thing.

Replace specific element in array

Some time we need to remove the specific value from the array while coding. Splice() made this easy to us. We already discuss above about the syntax and functionality of splice function.

Map an array without using map()

As we already discussed about the map function use, syntax and where we use this, so now we age going to check how to map and array without using map().

let subjects = [
{ name: 'Science', class: 1 },
{ name: 'Maths', class: 2 },
{ name: 'English', class: 3 },
]
console.log(Array.from(subjects, ({name}) => name));//output
["Science", "Maths", "English"]

Empty an array

It’s very simple to empty an array, we just need to set the length of an array to 0. let’s try

let fruits = ["banana", "mango", "grapes", "orange", "mango"];
fruits.length = 0;
console.log(fruits)//output
[]

Fill array with data

fill() function comes when we need to fill some data or we need to fill same values to array.

var dataArr = new Array(10).fill("1");
console.log(dataArr)
//output
["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]

Merge two or more arrays

We can merge the two or more arrays using the concat() function. We already discuss about concate() functionality and syntax above, please refer to that.

Reverse an array

If we need to reverse our array there is no need to use the loop, we can achieve this easily by using the reverse function. Let’s check example

let fruits = ["banana", "mango", "grapes", "orange", "mango"];
console.log(fruits.reverse());
//output
["mango", "orange", "grapes", "mango", "banana"]

I have covered most of the array functions in this article and will continuously add more. Feel free to comment if I miss any function, I will add that.

Happy Coding!!

--

--