Skip to content

Instantly share code, notes, and snippets.

@munkacsitomi
Last active February 3, 2022 10:37
Show Gist options
  • Save munkacsitomi/95ae44e151c9a3b72a6bad1e2218f4e6 to your computer and use it in GitHub Desktop.
Save munkacsitomi/95ae44e151c9a3b72a6bad1e2218f4e6 to your computer and use it in GitHub Desktop.
Array utilities
// 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