24
5 Useful Array Methods in Javascript
Hi, I'm Aya Bouchiha today, I'm going to talk about useful Array methods in Javascript.
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
);
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
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 = "[email protected]";
const hiddenEmailAddress = emailAddress.split("").fill("*", 2, 15).join("");
console.log(hiddenEmailAddress); // de*************@gmail.com
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 ]
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
- 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
Have a nice day!
24