Last active
March 24, 2021 00:56
-
-
Save wolftrax5/8e995914837bc72cd191fde31482cb04 to your computer and use it in GitHub Desktop.
Array Tools
This file contains 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
/* | |
combine 2 arrays | |
*/ | |
const addMoreItemsInArray = (array = [], newItems = []) => [...array, ...newItems]; |
This file contains 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
/* | |
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'); | |
This file contains 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
/* | |
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