Jun 28

Essential javascript array functions

Javascript is rich with its array datatype. It has lot of array function which can help you to manipulate your data at your finger tips.

Main goal for any app is to manage data and show user relevent data. These functions can be really useful and optimised to work with array. It can also reduce code size if used at relevent places.

let's check them out

Array element functions


Push()

Push function is used to add new element to the array. you can add single item at a time to array or you can add multiple item to array directly.

These items could be anything string, number, boolean or even another array.

push() function example
let jsArray = [];
// pushing string
jsArray.push('tutorialmeta.com');
// pushing boolena
jsArray.push(true);
// pushing object
jsArray.push({
    title: 'push function',
    description: 'JS array push function'
});
// pushing other Array
jsArray.push(['apple', 'banana']);
Push function in action

javascript-pish

Splice()

splice() method changes the existing array's contents by removing, replacing or adding existing elements in place.

This function modifies current array and operation index is zero(0) based.
splice() function example
let array = ['item 1', 'item 2', 'item 3'];
// adding new item at 2nd place / 1st index
array.splice(1, 0, 'new item 1');
// removing single item and return it from 3rd place / 2nd index
array.splice(2, 1);
Splice function in action

javascript-push

Array iteration functions


forEach()

Some time you just want to simply iterate over array element and forEach just might right for you.

forEach() function example
let array = ['item 1', 'item 2', 'item 3'];
// index is based on zero
array.forEach((item, index) => {
    console.log(`Item => "${item}", Index => ${index}`);
});
Index is zero(0) based.
forEach function in action

javascript-for-each

map()

Foreach function is great for iterating through each element but sometime you want create just new array instead modifying old one. Here this map function is very use ful.

map() function example
let array = [1, 2, 3];
// index is based on zero
let newArray = array.map((item, index) => {
    console.log(`Item => "${item}", Index => ${index}`);
    return item * 2;
});
// newArray will be [2, 4, 6]
map function in action

javascript-map

Array search functions


We learn all modification and interartion through array but sometime we just want to search through array. You can do it with forEach function but there are some other cool and elegent methods for that.

find()

If you want to check specific item is exist in array or not you can use this function.

It will return founded item if it found item in array basde on our function specified. if you return true from funcion it considered as item is found.

find() function example
let array = [1, 2, 3];
// index is based on zero
let foundItem = array.find((item) => item === 2);
// foundItem will be `founded item` in our case its `2`
let foundItem = array.find((item) => item === 20);
// foundItem will be `undefined` as item is not in array
find function in action

javascript-find

findIndex()

It is same function as find but differene is that it return's index of found element rather its value

It will return founded item index if it found item in array basde on our function specified. if you return true from funcion it considered as item is found.

findIndex() function example
let array = [1, 2, 3];
// index is based on zero(0)
let foundIndex = array.findIndex((item) => item === 2);
// foundIndex will be `1` index is based on 0
findIndex function in action

javascript-find-index

indexOf()

If you want to find specific index of an item based on item it self then you can use this function.

indexOf will return index of item if its avaliable in array, if item is not found it will return -1.

indexOf() function example
let array = [1, 2, 3];
// index is based on one(1)
let foundIndex = array.indexOf(2);
// foundIndex will be `1` index is based on 0

Also notice we are passing direct item not function for search

Index is one(1) based when returning found Index value.
indexOf function in action

javascript-index-of

Array aggregation and filter function


We are dealing with lot of data and sometime we need to find sum/total of items or sometime we need to filter items based on condition, at that time these function can be handy.

reduce()

This function will iterate over all the elements and gives you opportunity collection element's details in single variable For ex: sum of all available items in inventory.

reduce() function example
let array = [{ count: 10}, { count: 20}, { count: 30}];
let accDefaultValue = 0;
let total = array.reduce((accumulator, currentItem) => { 
    accumulator = accumulator + currentItem.count;
    // this accumulator will passed to next function until end
    return accumulator; 
}, accDefaultValue);
// total will be `60`
You can provide initial value of `accumulator` here we passed `0`.
reduce function in action

javascript-reduce

filter()

This function is widely used because of its nature. it filters array items based on given condition.

filter() function example
let array = [
    { title: 'item 1', active: true}, 
    { title: 'item 2', active: false}, 
    { title: 'item 3', active: true}, 
];
// here we want to have only active items
let filterdArray = array.filter(item => item.active === true);
// filterdArray will have `item 1` and `item 2` as they are active

Note that it won't affect your old array instead it will return new filtered array.

If you return `true` from function item will stay in array. if you return `false` item get removed from array.
filter function in action

javascript-filter

Array conditional function


By far we did all kind of manupulations, filtering and searching from array. now let's check some function which can help us to make conditional flows.

includes()

This function will check if avaialble item is in array or not based on that if will give is true or false.

includes() function example
let array = [12,34,66];
let is12InArray = array.includes(12); // will return true
let is100InArray = array.includes(100); // will return false
includes function in action

javascript-includes

some()

Sometime we want to check all of the values and make decisions rather specific single value. For ex: if we need to check array if any one of element is greater then 15.

So, basicaly if any one element of array is statifying condition it will return true

some() function example
let array = [12,10,7,3,2,19,11];
let hasValGraterThan15 = array.some((item) => item > 15);
// hasValGraterThan15 will be `true` as 19 > 15
let hasValGraterThan20 = array.some((item) => item > 20);
// hasValGraterThan20 will be `false` as nothing is > 20.
some function in action

javascript-some

every()

opposite of some function this function will require every elemet to satisfy condition then only it will return true.

If any of one do not satisfy conition it will return false.

every() function example
let array = [12,10,7,3,2,19,11];
let allEmemAreInlimitOf15 = array.some((item) => item > 15);
// allEmemAreInlimitOf15 will be `false` as one element 19 is > 15
let allEmemAreInlimitOf20 = array.some((item) => item > 20);
// allEmemAreInlimitOf20 will be `true` as every element is < 20.
every function in action

javascript-every

Conclusion


These functions are essential functions and must if you want o advance your knowledge of javascript coding. It is not just providing you greate flexibility, it also provides you optimised, small, extendable and readable way of writing your code.

We have just scratch the surface. We can do much more using these functions, we will check each of them in grater details in up coming new tutorials.

Ad
Ad