Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 7, 2022 11:01 am GMT

JavaScript Array Methods You Should Know

Hi everyone, Welcome to today's blog post. Today I'm going to share some tips about JavaScript arrays. When we are using JavaScript arrays we need to modify the array, find items in the array, insert new items into the array, remove items from the array, and many more. So we can use JavaScript built-in array methods to do the modifications to the arrays according to our requirements.


In this article, I'm demonstrating 24 JavaScript Array Methods. To demonstrate the 1 to 6 methods as an example I'll use the below array. In each method, I'll show the code snippet and output result.

const items = [ { name: "Apple", emoji: "", price: 50 }, { name: "Grapes", emoji: "", price: 30 }, { name: "Lemon", emoji: "", price: 40 }, { name: "Strawberry", emoji: "", price: 80 }, { name: "Banana", emoji: "", price: 10 }, { name: "Watermelon", emoji: "", price: 100 }, { name: "Mango", emoji: "", price: 20 }, { name: "Pineapple", emoji: "", price: 150 },];

1. find() Method
This method is used to get the value of the first element in the array that satisfies the provided condition.

const findItem = items.find((item) => {  return item.name === "Strawberry"})console.log(findItem)//RESULT//{ name: "Strawberry", emoji: "", price: 80 }

2. filter() Method
By using the filter method it returns an array with the values that pass the filter.

const filterItem = items.filter((item) => {  return item.price > 120})console.log(filterItem)//RESULT//[{ name: "Pineapple", emoji: "", price: 150 }]

3. map() Method
This method is used to iterate over an array and calling function on every element of array.

const mapItems = items.map((item) => {  return item.emoji})console.log(mapItems)//RESULT//["", "", "", "", "", "", "", ""]

4. forEach() Method
The forEach method is also used to loop through arrays, but it uses a function differently than the classic for loop. It passes a callback function for each element of an array together with the current value (required), index (optional) & array (optional).

//Method - 01items.forEach(demostrateforEach)function demostrateforEach(item, index, arr){  console.log(item)  console.log(index)  console.log(arr)}//Method - 02items.forEach((item, index, array) => {  console.log(item, index, array)})//RESULT FOR BOTH METHODS/*{name:"Apple", emoji:"", price:50} 0(8) [{...},{...},{...},{...},{...},{...},{...},{...}]{name:"Grapes" ,emoji:"", price:30}1(8) [{...},{...},{...},{...},{...},{...},{...},{...}]{name:"Lemon", emoji:"", price:40}2(8) [{...},{...},{...},{...},{...},{...},{...},{...}]etc...*/

5. some() Method
The some() method checks if any array elements pass a test (provided as a function). This method returns true if the function returns true for minimum one element. The method returns false if the function returns false for all elements.

  • Function returns true for minimum one element -> Method returns true

  • Function returns false for all elements -> Method returns false

const hasItemsPriceUpto80 = items.some((item) => {  return item.price > 80})console.log(hasItemsPriceUpto80)//RESULT//true

6. every() Method
This method executes a function for each array element. This method returns true if the function returns true for all elements. The method returns false if the function returns false for one element.

  • Function returns true for all elements -> Method returns true

  • Function returns false for one element -> Method returns false

const hasItemsPriceUpto80 = items.every((item) => {  return item.price > 80})console.log(hasItemsPriceUpto80)//RESULT//false

7. reduce() Method
This method apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.

const items = [2, 8, 1, 3, 5, 1, 10]const itemSum = items.reduce((result, currentValue) => {    return result + currentValue ;});console.log(itemSum);//RESULT//30

8. includes() Method
The includes() method determines whether a string contains the given characters within it or not. This method returns true if the string contains the characters, otherwise, it returns false. This method is case sensitive.

const items = ["", "", "", "", "", "", ""]const checkIncludes = items.includes("")console.log(checkIncludes)//RESULT//true

9. reverse() Method
This method reverse the order of the array. The first array element becomes the last, and the last array element becomes the first.

const items = ["", "", "", "", "", "", ""]const reverseItems = items.reverse()console.log(reverseItems)//RESULT//["", "", "", "", "", "", ""]

10. toString() Method
This method returns a string representing the array and its elements.

const items = ["", "", "", "", "", "", ""]const stringItems = items.toString()console.log(stringItems)//RESULT//",,,,,,"

11. join() Method
This method is allowed joins all elements of an array into a string.

const items = ["", "", "", "", "", "", ""]const itemsJoinCommas = items.join()console.log(itemsJoinCommas)//RESULT//",,,,,,"const itemsJoinDash = items.join('-')console.log(itemsJoinDash)//RESULT//"------"const itemsJoinAll = items.join('')console.log(itemsJoinAll)//RESULT//""

12. splice() Method
This method allows adds and/or removes elements from an array. When we use splice(4) will start removing elements from index 4. We can also define how many elements we want to remove from the array by passing a second number argument. In a example when we use splice(4, 2) will start removing only two elements from index 4.

const items = ["", "", "", "", "", "", ""]const itemsSplice = items.splice(4);console.log(itemsSplice )//RESULT//["", "", ""]const itemsSpliceSpecificNumber = items.splice(4, 2);console.log(itemsSpliceSpecificNumber)//RESULT//["", ""]

13. slice() Method
This method allows extracts a section of an array and returns a new array.

const items = ["", "", "", "", "", "", ""]// slicing the array from start to endconst itemSliceAll = items.slice();console.log(itemSliceAll)//RESULT//["", "", "", "", "", "", ""]// slicing from the fourth elementconst itemSlice = items.slice(3);console.log(itemSlice)//RESULT//["", "", "", ""]// slicing from the fourth element to fifth elementconst itemSliceSpecificNumber = items.slice(3, 5);console.log(itemSliceSpecificNumber)//RESULT//["", ""]

14. indexOf() Method
This method returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

const items = ["", "", "", "", "", "", ""]const indexItem = items.indexOf("")console.log(indexItem)const newItem = items.indexOf("")console.log(newItem)//RESULT//3//-1

15. findIndex() Method
This method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.

const items = ["", "", "", "", "", "", ""]const findIndexItemOne = items.findIndex((item) => {    return item === ""});console.log(findIndexItemOne)//RESULT//3const findIndexItemTwo = items.findIndex((item) => {    return item === ""});console.log(findIndexItemTwo)//RESULT//-1

16. lastIndexOf() Method
This method returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

const items = ["", "", "", "", "", "", ""]const lastIndexItem = items.lastIndexOf("")console.log(lastIndexItem)const newItem = items.lastIndexOf("")console.log(newItem)//RESULT//5//-1

17. concat() Method
This method allows returns a new array comprised of this array joined with other array(s) and/or value(s).

const itemOne = ["", "", "", ""]const itemTwo = ["", "", ""]const itemsArray = itemOne.concat(itemTwo)console.log(itemsArray)//RESULT//["", "", "", "", "", "", ""]

18. push() Method
This method allows adds one or more elements to the end of an array and returns the new length of the array.

const items = ["", "", "", "", "", "", ""]const pushItem = items.push('')console.log(pushItem)console.log(items)//RESULT//8//["", "", "", "", "", "", "", ""]

19. pop() Method
This method allows removes the last element from an array and returns that element.

const items = ["", "", "", "", "", "", ""]const popItem = items.pop()console.log(popItem)console.log(items)//RESULT//""//["", "", "", "", "", ""]

20. shift() Method
This method removes the first element from an array and returns that element.

const items = ["", "", "", "", "", "", ""]const shiftItem = items.shift()console.log(shiftItem)console.log(items)//RESULT//""//["", "", "", "", "", ""]

21. unshift() Method
This method allows adds one or more elements to the front of an array and returns the new length of the array.

const items = ["", "", "", "", "", "", ""]const unshiftItem = items.unshift("")console.log(unshiftItem)console.log(items)//RESULT//8//["", "", "", "", "", "", "", ""]

22. isArray() Method
This method check whether an object or a variable is an array or not. isArray() method returns true if the value is an array, if not returns false .

const itemArray = ["", "", "", "", "", "", ""]const isItemsArray = Array.isArray(itemArray)console.log(isItemsArray)//RESULT//trueconst itemObject = {"" : "Apple", "" : "Grapes"}const isSample2Array = Array.isArray(itemObject)console.log(isSample2Array)//RESULT//falseconst itemString = "Apple"const isSample3Array = Array.isArray(itemString)console.log(isSample3Array)//RESULT//false

23. length Property
The length property of an object which is an instance of type Array sets or returns the number of elements in that array.

const items = ["", "", "", "", "", "", ""]const itemsLength = items.length;console.log(itemsLength )//RESULT//7

Original Link: https://dev.to/samithawijesekara/javascript-array-methods-you-should-know-3c2h

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To