Skip to content

Instantly share code, notes, and snippets.

@wolftrax5
Last active March 24, 2021 00:56
Show Gist options
  • Save wolftrax5/8e995914837bc72cd191fde31482cb04 to your computer and use it in GitHub Desktop.
Save wolftrax5/8e995914837bc72cd191fde31482cb04 to your computer and use it in GitHub Desktop.
Array Tools
/*
combine 2 arrays
*/
const addMoreItemsInArray = (array = [], newItems = []) => [...array, ...newItems];
/*
From a Array of objects
const array = [
{ id: 'd5fe012d-c344-49cd-a4f4-b3c56a7f04c8', name: 'lalalala' },
{ id: '3c66c9ce-7b92-45ba-8684-cce8f18da1bd', name: 'lolololo' },
{ name: 'lelelele' },
];
getItemById(array, 'd5fe012d-c344-49cd-a4f4-b3c56a7f04c8')
return // { id: 'd5fe012d-c344-49cd-a4f4-b3c56a7f04c8', name: 'lalalala' }
*/
const getItemBy = (param) => (array, value) => array.find((elment) => elment[param] === value);
export const getItemById = getItemBy('id');
/*
with array of objects, return a array with non repeat item
testObject = { id: 2, name: 'foo' };
addNoRepeatItems([testObject], [{ id: 3, name: 'off' }], 'name')
// [{ id: 3, name: 'off' }, { id: 2, name: 'foo' }];
addNoRepeatItems([testObject], [{ id: 4, name: 'off' }], 'name')
// [{ id: 3, name: 'off' }, { id: 2, name: 'foo' }];
*/
const addNoRepeatItems = (array, newItem, comp = 'id') => {
// store the comparison values in array
const arr = [newItems, ...array];
const unique = arr
.map((e) => e[comp])
// store the indexes of the unique objects
.map((e, i, final) => final.indexOf(e) === i && i)
// eliminate the false indexes & return unique objects
.filter((e) => arr[e])
.map((e) => arr[e]);
return Array.from(unique);
/*
const arr = [newItem, ...array]
return arr.filter((e, i) => arr.findIndex(a => a[comp] === e[comp]) === i);
*/
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment