Last active
February 3, 2022 10:37
-
-
Save munkacsitomi/95ae44e151c9a3b72a6bad1e2218f4e6 to your computer and use it in GitHub Desktop.
Array utilities
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
// Compares 2 arrays of (primitive) values to see if they are the same | |
const doArraysMatch = (arr1, arr2) => arr1.length === arr2.length && arr1.every((element) => arr2.includes(element)); | |
// Reusable function to combine arrays | |
const mergeArr = (...arr) => arr.reduce((acc, val) => [...acc, ...val], []); | |
// Group an array of objects by a specific key or property value | |
const movies = [ | |
{ title: 'Test 1', year: 2020 }, | |
{ title: 'Test 2', year: 2020 }, | |
{ title: 'Test 3', year: 2021 } | |
]; | |
const groupBy = (arr, criteria) => { | |
return arr.reduce((acc, currentValue) => { | |
if (!acc[currentValue[criteria]]) { | |
acc[currentValue[criteria]] = []; | |
} | |
acc[currentValue[criteria]].push(currentValue); | |
return acc; | |
}, {}); | |
} | |
const moviesByYear = groupBy(movies, 'year'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment