0

I am trying to add an object to an array if the array already does not have that object.

So I have an array as follows

[{id:1},{id:2},{id:3}]

I want to check if a id:1 exist or not if not then add if yes then show an error or log a message.

I am able to achieve this using a simple array as follows.

let result =[1,2,2,3,1,4,1,4,2,3].filter((el, i, a) => i === a.indexOf(el));

I cannot figure out how to achive the same with array of objects.

Thanks

1
  • It seems that you might be running into problems trying to compare objects. Objects in JavaScript are considered equal only if they refer to the same object. This means that {id:1} == {id:1} returns false. You might need to define your own way of comparing objects. JSON.stringify(obj1) === JSON.stringify(obj2) could work for simple JSON stringifiable objects. More info eg. here: stackoverflow.com/questions/1068834/…. Commented Jan 16, 2018 at 15:28

3 Answers 3

2

You can use some to check for duplicates like:

// array with duplicate objects {id:1}
let arr = [{id:1},{id:1},{id:2}]
function duplicateFound(arr){
  const ids = arr.map(x => x.id);
  return ids.some((item, idx) => ids.indexOf(item) != idx);
}
console.log(duplicateFound(arr));

// array with not duplicates
arr = [{id:1},{id:2},{id:3}]
console.log(duplicateFound(arr));

Sign up to request clarification or add additional context in comments.

3 Comments

If you want to check if an array contains any duplicates, you can do: new Set(ids).size !== ids.length
@OriDrori will java script Set work with complex json array object , where i should compare each json key value for the duplicate? for e.g `{ "employee": { "name": "sonoo", "salary": 56000, "married": true } } ´
If you want to dedupe an array of objects, you can reduce to a Map, using the unique key (id for example) as the Map's item key, and then convert back to an array.
2

You can use Array#filter, and check the length:

const arr = [{id:1},{id:2},{id:3}];
const el = { id: 1 };
const exists = arr.filter(({ id }) => id === el.id).length > 0;

console.log(exists);

Or you can use Array#find, which has a slight advantage over Array#filter, since it will stop as soon as an item was found.

const arr = [{id:1},{id:2},{id:3}];
const el = { id: 1 };
const exists = !!arr.find(({ id }) => id === el.id);

console.log(exists);

You can wrap your array with a proxy that has a set trap, to prevent the insertion of duplicates automatically:

const arr = [{id:1},{id:2},{id:3}];

const arrayChangeHandler = {
  set: function(target, property, value, receiver) {
    if(property === 'length') {
      return true;
    }
    
    const exists = !!target.find(({ id }) => id === value.id);
    if(exists) {
      console.log(`Id: ${value.id} exists!`); // you can return false here, and it will throw an error
    } else {
      target.push(value);
    }
        
    return true;
  }
};
  
const pArr = new Proxy(arr, arrayChangeHandler);

pArr.push({ id: 1 });
pArr.push({ id: 10 });

console.log(JSON.stringify(arr));

Comments

0

You could try inserting all values as keys to a new array then flip keys & vals

let arr = "abccba".split('');

let res = [];

arr.forEach((n) => {
    res[n] = n;
});

console.log(Object.keys(res));

A concern might be that if your values are numbers then you might need to recast them eg.

res = res.map(n) => +n

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.