Array Operations in JavaScript
Hi everyone, in this article, I will try to explain array operations in JavaScript. Maybe you can find too many blog posts and videos about…
Hi everyone, in this article, I will try to explain array operations in JavaScript. Maybe you can find too many blog posts and videos about this topic but I took note of myself and wanted to share it.
forEach
forEach is the function that you can reach the items in an array. That does not give you a new array or one element in return. This function allows you to make an operation in the list. Just iterates all items in the list.
filter
You can filter items with ‘filter’ method according to if statement. And filter method returns back type of array. As you can see in below example we have an array which has 5 items. I used filter method for getting words which is letter count is less than 4. And just ‘css’ has less thank 4 letter.
map
You can create new array with existing elements of array using map function. You can use every element of array in function. For example you have table in the page and you need get items in array and change them. For this operation you can use the map function.
includes
You can check the element is include in the array or not with ‘includes’ function. In below example i checked the array has ‘okan’ item or not.
find
You can get the one element in the array with find function. Like in filter method you are giving some condition to find and it gives you first element in the array that matches with your condition. You can also use filter method for getting first finding of element. But difference of it is ‘find’ function stops the iterating after found the item.
Also one more difference between find and filter is the find() method doesn’t work in IE <= 11 but the filter() method works in all browsers (IE9+).
sort
You can sort items in array according the your requirements with sort function. In the below example, for string array it sorted according the ascending. And for the second number array example we gave the parameters of sort method.
every
You can check all items match with your condition using every function. In below example we checked all items length are 4 or not. Function iterated all items and checked the items is 4 letter or not.
some
You can check one of the array items is match with your condition or not with ‘some’ method. Difference with the every is when the element found then ‘some’ method stops the iterating the list. So it’s better for performance.
In this article, I have tried to talk about array methods as much as I can. I can make additions here in the future. You can reach all the codes in here.
Thank you for reading. Sharing and applause will increase motivation :).