I just wanted to share my newly created JavaScript code. This code is responsible for passing back only the unique elements for a given array. This one is quite useful when you have a huge array and you store objects with huge arrays.
Use case: you want to sort out all unique object to do provide a filtering mechanism based on the chips!
Like the array is the following:
[
{
"name": "custom object1",
"chips": [
{
"name": "hello"
},
{
"name": "war"
}
]
},
{
"name": "custom object2",
"chips": [
{
"name": "hello"
},
{
"name": "option"
}
]
}
]
The function:
function getUnique(array, props, level = 0) {
var retArray = [];
array.forEach(function (element) {
var index = props[level];
if (Array.isArray(props) && props.length - 1 > level) {
if (element[index] !== undefined) {
var res = getUnique(element[index], props, level + 1);
res.forEach(function (subelement) {
if (!retArray.some(function (arrayItem) {
return arrayItem === subelement;
})) {
retArray.push(subelement);
}
});
}
} else {
if (element[index] !== undefined && !retArray.some(function (arrayItem) {
return arrayItem === element[index];
})) {
retArray.push(element[index]);
}
}
});
return retArray;
}
How to call the function:
getUnique(array, ['chips', 'name']);
That's it in a nutshell. What do you think? Any suggestions or advice?