Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 20, 2021 11:46 pm GMT

5 Useful Array Methods in Javascript

Hi, I'm Aya Bouchiha today, I'm going to talk about useful Array methods in Javascript.

every

every(callbackFunction): returns true if all elements in an array pass a specific test, otherwise, returns false

const allProductsPrices = [21, 30, 55, 16, 46];// false because of 16 < 20const areLargerThanTwenty = allProductsPrices.every(    (productPrice) => productPrice > 20);// true because allProductsPrices < 60const areLessThanSixty = allProductsPrices.every(    (productPrice) => productPrice < 60);

some

some(callbackFunction): returns true if at least one element in the array passes a giving test, otherwise, it returns false.

const allProductsPrices = [10, 0, 25, 0, 40];const isThereAFreeProduct = allProductsPrices.some(    (productPrice) => productPrice === 0);const isThereAPreciousProduct = allProductsPrices.some(    (productPrice) => productPrice > 100);console.log(isThereAFreeProduct); // trueconsole.log(isThereAPreciousProduct); // false

fill

fill(value, startIndex = 0, endIndex = Array.length) : fills specific elements in an array with a one giving value.

const numbers = [20, 254, 30, 7, 12];console.log(numbers.fill(0, 2, numbers.length)); // [ 20, 254, 0, 0, 0 ]// real exampleconst emailAddress = "[email protected]";const hiddenEmailAddress = emailAddress.split("").fill("*", 2, 15).join("");console.log(hiddenEmailAddress); // de*************@gmail.com

reverse

reverse(): this method reverses the order of the elements in an array.

const descendingOrder = [5, 4, 3, 2, 1];// ascendingOrderconsole.log(descendingOrder.reverse()); // [ 1, 2, 3, 4, 5 ]

includes

includes(value, startIndex = 0): is an array method that returns true if a specific value exists in a giving array, otherwise, it returns false (the specified element is not found).

const webApps = ["coursera", "dev", "treehouse"];console.log(webApps.includes("dev")); // trueconsole.log(webApps.includes("medium")); // false

Summary

  • every(callbackFunction): returns true if all elements in an array passed a giving test.
  • some(callbackFunction): returns true if at least one element passed a giving test.
  • fill(value, startIdx = 0, endIdx = arr.length): fills specified array elements with a giving value.
  • reverse(): reverses the order of the elements in an array.
  • includes(value, startIdx = 0): check if a giving value exist in an specific array

References

Have a nice day!


Original Link: https://dev.to/ayabouchiha/5-useful-array-methods-in-javascript-43c8

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