Skip to content

Instantly share code, notes, and snippets.

@munkacsitomi
Last active March 8, 2019 15:20
Show Gist options
  • Save munkacsitomi/f9ec4bdf050bb53c021f9965edf91838 to your computer and use it in GitHub Desktop.
Save munkacsitomi/f9ec4bdf050bb53c021f9965edf91838 to your computer and use it in GitHub Desktop.
Built-in array methods
const arr = [1, 2, 3, 4, 5, 6];
// forEach()
arr.forEach(item => {
console.log(item); // output: 1 2 3 4 5 6
});
// includes()
arr.includes(2); // output: true
arr.includes(7); // output: false
// filter()
// item(s) greater than 3
const filtered = arr.filter(num => num > 3);
console.log(filtered); // output: [4, 5, 6]
console.log(arr); // output: [1, 2, 3, 4, 5, 6]
// map()
// add one to every element
const oneAdded = arr.map(num => num + 1);
console.log(oneAdded); // output [2, 3, 4, 5, 6, 7]
console.log(arr); // output: [1, 2, 3, 4, 5, 6]
// reduce()
const sum = arr.reduce((total, value) => total + value, 0);
console.log(sum); // 21
// some()
// at least one element is greater than 4?
const largeNum = arr.some(num => num > 4);
console.log(largeNum); // output: true
// at least one element is less than or equal to 0?
const smallNum = arr.some(num => num <= 0);
console.log(smallNum); // output: false
// every()
// all elements are greater than 4
const greaterFour = arr.every(num => num > 4);
console.log(greaterFour); // output: false
// all elements are less than 10
const lessTen = arr.every(num => num < 10);
console.log(lessTen); // output: true
// sort()
const alpha = ['e', 'a', 'c', 'u', 'y'];
// sort in descending order
descOrder = arr.sort((a, b) => a > b ? -1 : 1);
console.log(descOrder); // output: [6, 5, 4, 3, 2, 1]
// sort in ascending order
ascOrder = alpha.sort((a, b) => a > b ? 1 : -1);
console.log(ascOrder); // output: ['a', 'c', 'e', 'u', 'y']
// find()
arr.find(item => item > 2); // output: 6
// findIndex()
arr.findIndex(item => item > 2); // output: 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment