0

In this post Get all unique values in a JavaScript array (remove duplicates) one of the answers shows how to get unique items for an object array based on a value of a field (shown below), but it is in ES6 notation and I need help converting it to ES5 (no arrows or elipses).

let objArr = [{
  id: '123'
}, {
  id: '123'
}, {
  id: '456'
}];

objArr = objArr.reduce((acc, cur) => [
  ...acc.filter((obj) => obj.id !== cur.id), cur
], []);

console.log(objArr);

3 Answers 3

2

i hope this help

var objArr = [{
  id: '123'
}, {
  id: '123'
}, {
  id: '456'
}];

var newObjArr = objArr.reduce(function(previous, current){
    var alredyExists = previous.filter(function(item){
        return item.id === current.id
    }).length > 0
    if(!alredyExists){
        previous.push(current)
    }
    return previous
}, [])

console.log(newObjArr)
Sign up to request clarification or add additional context in comments.

Comments

2

let objArr = [{ id: '123' }, { id: '123' }, { id: '456' }]


objArr = objArr.reduce(function (acc, cur) {
    return acc.filter(function (obj) {
        return obj.id !== cur.id
    }).concat([cur])
}, [])

console.log(objArr)

Comments

0

You can use reduce method and map function:

let unique = objArr.reduce(function(a, c){
    a[c.id] = a[c.id] || {};
    a[c.id] = c.id;
    return a;
},{})

console.log(Object.values(unique).map(function(s){return {id: s}}))

An example:

let objArr = [{
  id: '123'
}, {
  id: '123'
}, {
  id: '456'
}];

let unique = objArr.reduce(function(a, c){
	a[c.id] = a[c.id] || {};
    a[c.id] = c.id;
	return a;
},{})

console.log(Object.values(unique).map(function(s){return {id: s}}))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.