Reputation: 107
I've looked through many stack overflow questions, but none seem to quite answer my question. I have an array of objects, which I would like to reduce by deleting all objects where the key and value are the same.
So my array of objects would be:
[{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]
The end result should be:
[{a:1},{a:2},{c:3},{b:1},{c:4}]
I've tried using filer and map, but I can only get the first object in the array, rather than all the objects that have different key/value pairs in the array. I've also tried using filter and findIndex, but with the same problem.
I also can't filter the objects before pushing them into the array.
Can someone point me in the right direction?
Upvotes: 2
Views: 3521
Reputation: 73
Assuming that all your object are of different types(different properites) and are not complex in nature i.e., not nested objects..
Create a array list(which will act as multi dimensional array).
let uniqueArr = [];
Loop through your array which contains duplicates with Arr.forEach();
Get property of the object using
Object.getPropertyNames(item)
;
uniqueArr.push({property:[]})
;
Sample : uniqueArr [ {a:[1,2]}, {b:[1]}, {c:[3]} ];
Upvotes: 0
Reputation: 36351
You can compare the two items using JSON.stringify(). We then add to a new array using reduce, if it is in the array we don't add it otherwise we do add it.
const array = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]
let unique = array.reduce((res, itm) => {
// Test if the item is already in the new array
let result = res.find(item => JSON.stringify(item) == JSON.stringify(itm))
// If not lets add it
if(!result) return res.concat(itm)
// If it is just return what we already have
return res
}, [])
console.log(unique)
Alternatively you could use a Set (as Fissure King metions) to make a unique list of items like this:
const array = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]
let unique = [...new Set(array.map(itm => JSON.stringify(itm)))].map(i => JSON.parse(i))
console.log(unique)
Upvotes: 3
Reputation: 1195
var a = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}];
var newData = [];
a.map(ele=>JSON.stringify(ele)).forEach(ele=>{
if(newData.indexOf(ele) === -1){
newData.push(ele)
}
});
newData.map(ele=>JSON.parse(ele))
console.log(newData);
Upvotes: -1