My Top 5 JavaScript Array Methods

Helpful? Yes. Needed? Sometimes. Should you know them? Absolutely.

What are JavaScript methods?

someArray.nameOfMethod() // pseudocode

Methods

const numbers = [1, 2, 3];
const strings = ["hello", "world"];
numbers.includes(1) // returns true
numbers.includes(4) // returns false
numbers.includes(2, 1) // search for 2 from index 1. returns true
numbers.includes(1, 2) // search for 1 from index 2. returns false
strings.includes("hello") // returns true
strings.includes("javascript") // returns false
const someArray = [1, 2, 3];someArray.forEach(element => console.log(element + 5));// output -> 6
// output -> 7
// output -> 8
someArray.forEach((element, idx) => console.log(element + 5, idx));// output -> 6 0
// output -> 7 1
// output -> 8 2
const someArray = [3, 6, 9];const newArray = someArray.map(element => element * 5);console.log(newArray);
// output -> [15, 30, 45]
const anotherArray = newArray.map((element, idx) => {
console.log(idx);
return element + 1
}
// output -> 0
// output -> 1
// output -> 2
console.log(anotherArray)
// output -> [16, 31, 46]
const numbers = [20, 10, 30];
const words = ["hello", "world", "learn", "javascript"];
const filteredNum = numbers.filter(number => number >= 20);console.log(filteredNum);
// output -> [20, 30]
const filteredWords = words.filter(word => word.length > 5);console.log(filteredWords);
// output -> ["javascript"];
const numbersAgain = [1, 2, 3, 4, 5];const initialValue = 0;const reducer = (accumulator, currentValue) => {
console.log("acc is " + accumulator + " current value is " + currentValue);
return accumulator + currentValue
}
const sum = numbersAgain.reduce(reducer, initialValue);
// output -> acc is 0 current value is 1
// output -> acc is 1 current value is 2
// output -> acc is 3 current value is 3
// output -> acc is 6 current value is 4
// output -> acc is 10 current value is 5
console.log(sum);
// output -> 15

Conclusion

A Singaporean perspective. Sometimes I write. Sometimes I code. Mostly I watch lots of movies.