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 anythingstring, number, boolean or even another array
.
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']);
Splice()
splice()
method changes the existing array's contents by removing, replacing or adding existing elements in place.
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);
Array iteration functions
forEach()
Some time you just want to simply iterate over array element and forEach
just might right for you.
let array = ['item 1', 'item 2', 'item 3'];
// index is based on zero
array.forEach((item, index) => {
console.log(`Item => "${item}", Index => ${index}`);
});
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.
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]
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.
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
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.
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
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
.
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
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.
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`
filter()
This function is widely used because of its nature. it filters
array items based on given condition.
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
.
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
.
let array = [12,34,66];
let is12InArray = array.includes(12); // will return true
let is100InArray = array.includes(100); // will return false
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
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.
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
.
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.
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.
Related Questions
- → How to use ReactJS useLocalstorage hook
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → Alt @decorators in React-Native