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

krv
  • 2,830
  • 7
  • 40
  • 79
  • 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: https://stackoverflow.com/questions/1068834/object-comparison-in-javascript. – Petr Srníček Jan 16 '18 at 15:28

3 Answers3

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));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
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));
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • If you want to check if an array contains any duplicates, you can do: `new Set(ids).size !== ids.length` – Ori Drori Jan 16 '18 at 15:06
  • @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 } } ´ – Saradha Mar 12 '21 at 17:00
  • 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. – Ori Drori Mar 12 '21 at 17:44
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

Jacksonkr
  • 31,583
  • 39
  • 180
  • 284