## Array method cheatsheet Summarised from [this image by Владислав Иванов](https://www.facebook.com/photo/?fbid=5261247360643775&set=gm.1209633786362514&idorvanity=170643816928188) ```javascript a = [1,2,3,4] a.push(5) // [1,2,3,4,5] a.unshift(0) // [0,1,2,3,4,5] a.pop() // [0,1,2,3,4] -- returns 5 a.shift() // [1,2,3,4] -- returns 0 a.splice(pos,count) // remove count elements starting at pos b = [1,2,3,4,5] b.splice(1,3,"hello","world") // returns [2,3,4] and inserts ["hello","world"] in its place // b is now [ 1, 'hello', 'world', 5 ] b.reverse() // b is now [ 5, 'world', 'hello', 1 ] b.sort() // b is now [ 1, 5, 'hello', 'world ] b.sort((x,y) => Math.random()-0.5) // random shuffle idiom a.fill(2) // make every element of a 2 // fill and map a = (new Array(100)).fill().map((x,i) => i**2) a.sort((x,y) => Math.random()-0.5) // random shuffle idiom a = ["a","b","c"] a.map((x,i) => `
  • ${i}: ${x}
  • `) // returns [ '
  • 0: a
  • ', '
  • 1: b
  • ', '
  • 2: c
  • ' ] a.filter(x => x !== "b") // returns [ 'a', 'c' ] a.slice(10) // all elements from 10th onwards a.slice(10,15) // elements from 10th up to not including 15th // that is, [a[10],a[11],...,a[14]] a = [1,2,3] b = [4,5,6] a.concat(b) // returns [ 1, 2, 3, 4, 5, 6 ] a = [[1,2],[3,4]] a.flat() // returns [ 1,2,3,4 ] a = [ [ 1, 2 ] , [ 3 , 4 ] ] a.flatMap(x => x.concat(["hello"])) // returns [ 1, 2, 'hello', 3, 4, 'hello' ] // equivalent to: (a.map(x => x.concat(["hello"]))).flat() a = [ "a", "b", "c" ] a.indexOf("b") // returns 1 a.indexOf("c") // returns 2 a.find(x => x.match(/aw/[bc]/)) // find first element x such that x.match(/aw/[bc]/) returns true a.findIndex(x => x.match(/aw/[bc]/)) // index of first element x such that x.match(/aw/[bc]/) returns true // equivalent to: a.indexOf(a.find(x => x.match(/aw/[bc]/))) a.includes("d") // false a.includes("c") // true a.some(x => x.match(/aw/[ab]/)) // true a.every(x => x.match(/aw/[ab]/)) // false a.join(", ") // "a, b, c" a.forEach(x => console.log(x)) a = [ 1, 2, 3, 4, 5 ] a.reduce((x,y) => x*y, 1) // a.reduce(function, initial) // returns 120 ``` The image: ![JavascriptArrayMethods_001.jpg](JavascriptArrayMethods_001.jpg) ## Random Saw this on facebook: ![javascript array methods](javascript_array_methods_illustrated.jpg)