I have array of objects that look like:
{
"brandid": id,
"brand": string,
"id": id,
"categoryId": id,
"category": string,
"factory": string,
"series": string,
"status": 0,
"subStatus": 1
}
if the series property value matches another series property value in the other objects in the array, that object needs to be removed from the array.
Currently I have attempted to push them to a duplicate Array with :
const seriesResCopy = seriesRes;
const dupArray = []
for (const thing of seriesResCopy) {
for (const item of seriesRes) {
if (thing.series === item.series) {
dupArray.push(item);
}
}
}
but this does not work. From examples I have seem my issue has been that I do not have a definite list of duplicate values to look for.
Any help would be much appreciated.
You could use a Set of series to filter out duplicates:
const exists = new Set();
seriesRes = seriesRes.filter(({series}) => !exists.has(series) && exists.add(series));
This uses: Array.prototype.filter
, Object destructuring and some logical tricks.
The same can be done by mutating the array:
const exists = new Set();
for(const [index, {series}] of seriesRes.entries()) {
if(!exists.has(series) {
exists.add(series);
} else {
seriesRes.splice(index, 1);
}
}
To filter duplicates from the array and keep the first instance:
let seriesWithoutDuplicates = seriesRes.filter((s, i, self) => {
return self.findIndex(z => z.series === s.series) === i;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.