Last active
April 14, 2018 03:19
-
-
Save nikhilmetrani/cbc6056cb580fe63f103796a19ae8aca to your computer and use it in GitHub Desktop.
JavaScript - Array Methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const countDuplicates = arr => arr.reduce((acc, el) => { | |
acc[el] = (acc[el] || 0) + 1; | |
return acc; | |
}, {}); | |
countDuplicates(['a', 'a', 'b', 'c', 'd', 'd', 'd') // {a: 2, b: 1, c: 2, d: 3} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const diffArrays = (arr1, arr2) => [...arr1.filter(val => arr2.indexOf(val) === -1), ...arr2.filter(val => arr1.indexOf(val) === -1)]; | |
diffArray(['a', 'b', 'c', 'e'], ['a', 'b', 'c', 'd', 'e']); //['d'] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns a reverse array | |
const reverse = arr => [...arr].reverse(); | |
// flips rows with columns | |
const flip = matrix => matrix[0].map((column, index) => matrix.map(row => row[index])); | |
const rotate90 = matrix => flip(matrix).map(reverse); | |
const rotate180 = matrix => reverse(matrix).map(reverse); | |
const rotate270 = matrix => flip(matrix.map(reverse)); | |
rotate90([[1,2,3],[4,5,6],[7,8,9]]); // [[7,4,1],[8,5,2],[9,6,3]] | |
rotate180([[1,2,3],[4,5,6],[7,8,9]]); // [[9,8,7],[6,5,4],[3,2,1]] | |
rotate270([[1,2,3],[4,5,6],[7,8,9]]); // [[3,6,9],[2,5,8],[1,4,7]] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const pascalsTriangle = height => { | |
return Array(height) | |
.fill() | |
.reduce( | |
(acc, current, rowIdx) => { | |
acc.push( | |
Array(rowIdx+1) | |
.fill() | |
.map((val, colIdx) => (colIdx === 0 || colIdx === rowIdx) ? 1 : | |
acc[rowIdx-1][colIdx-1] + acc[rowIdx-1][colIdx] | |
) | |
); | |
return acc; | |
},[]); | |
} | |
pascalsTriangle(5); // [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment