DEV Community

Cover image for 5 Useful Array Methods in Javascript
Aya Bouchiha
Aya Bouchiha

Posted on

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 < 20
const areLargerThanTwenty = allProductsPrices.every(
    (productPrice) => productPrice > 20
);
// true because allProductsPrices < 60
const areLessThanSixty = allProductsPrices.every(
    (productPrice) => productPrice < 60
);
Enter fullscreen mode Exit fullscreen mode

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); // true
console.log(isThereAPreciousProduct); // false
Enter fullscreen mode Exit fullscreen mode

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 example
const emailAddress = "developer.aya.b@gmail.com";
const hiddenEmailAddress = emailAddress.split("").fill("*", 2, 15).join("");
console.log(hiddenEmailAddress); // de*************@gmail.com
Enter fullscreen mode Exit fullscreen mode

reverse

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

const descendingOrder = [5, 4, 3, 2, 1];
// ascendingOrder
console.log(descendingOrder.reverse()); // [ 1, 2, 3, 4, 5 ]
Enter fullscreen mode Exit fullscreen mode

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")); // true
console.log(webApps.includes("medium")); // false
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

Collapse
 
flagmans profile image
Flagmans

Very useful. Thank you.

Collapse
 
ayabouchiha profile image
Aya Bouchiha

You're always welcome !