0

I have an array of objects that I use for a materials table datasource. I need to see if this row already exists in the datasource array before adding it.

There is no key value in this array. So I need to check if all items are unique

var datasource = [
     { Name: Jon,  Address: 123 something }, {Name: Tyler , Address: 333 Something}

]

var rowtoAdd = [
     { Name: Jon,  Address: 123 something }

]

const found = datasource.find(x => x.name == rowtoAdd.Name && x.Address == rowtoAdd.Address)

Is there a better way?

CodeMan03
  • 570
  • 3
  • 18
  • 43
  • the rowtoAdd will be array or an object? – Shubham Feb 04 '20 at 02:51
  • Does this answer your question? [Object comparison in JavaScript](https://stackoverflow.com/questions/1068834/object-comparison-in-javascript) – zmag Feb 04 '20 at 02:56
  • @Shubham rowtoAdd will be pushed into the datasource array ONLY if it doesnt already exist. In my scenario it would already exist but I need a way to check if it does – CodeMan03 Feb 04 '20 at 03:34
  • @zmag It is similar if it were a 1:1 object array. but I need a 1:many comparison – CodeMan03 Feb 04 '20 at 03:34

1 Answers1

0

One way you can do this is by hashing the elements. Your current solution takes O(n) time each time you need to check. if you create a hashtable it will take 0(n) to create the table but the run time will O(1) for all consecutive run.

var datasource = [
     { "Name": "Jon",  "Address": "123 something" }, {"Name": "Tyler" , "Address": "333 Something"}

]

var map = datasource.reduce(function(map, obj) {
    map[obj.Name+obj.Address] = true;
    return map;
}, {});

rowtoAdd = { "Name": "Jon",  "Address": "123 something" }
if(!map[rowtoAdd.Name+rowtoAdd.Address])
datasource.push(rowtoAdd)

So, in sort reduce your array to a hashmap

Shubham
  • 189
  • 9