lang/js/ ArrayMethods1
Array method cheatsheet
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) => `<li>${i}: ${x}</li>`)
// returns [ '<li>0: a</li>', '<li>1: b</li>', '<li>2: c</li>' ]
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(/[bc]/)) // find first element x such that x.match(/[bc]/) returns true
a.findIndex(x => x.match(/[bc]/)) // index of first element x such that x.match(/[bc]/) returns true
// equivalent to:
a.indexOf(a.find(x => x.match(/[bc]/)))
a.includes("d") // false
a.includes("c") // true
a.some(x => x.match(/[ab]/)) // true
a.every(x => x.match(/[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
Random
Saw this on facebook: