Suraz Khanal
Suraz Khanal

Reputation: 222

How to merge two arrays in Javascript

First Array

[{'value':'one','other':'othervalue'},{value:'two'},{value:'three'},{value:'four'}]

Second Array

['one','two','six','five']

Here i want to add second array value to the first array's value attribute if there is unique .if dublicate exists code must skip that . I have tried with looping all the values like,

for( var i=0; i < eLength; i++ ) {
    for( var j = 0; j < rLength; j++ ) {
        if( temp[j].values != enteredValues[i] ) {

            console.log()

            var priority = enteredValues.indexOf( enteredValues[i] ) + 1;
            var obj = { 'values': enteredValues[i] };
        }
    }
    reportbody.push( obj) ;
}

Upvotes: 1

Views: 560

Answers (3)

user663031
user663031

Reputation:

Although there could be performance advantages in using a hash table or dictionary, the most straightforward implementation is

second.forEach(s => {
  if (!first.find(f => f.value === s)) first.push({value: s});
});

If you do want to use a hash table, semantically one might prefer to use a Set:

const dict = new Set(first.map(f => f.value));
second.forEach(s => { if (!dict.has(s)) first.push({value: s}); });

The above code will not handle duplicates in the second array, so if that is an issue you would need to adjust accordingly.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386578

You could use an object as hash table for the values in the object array by setting the object with looping data.

Then check if a value is in the array and if not push a new object to data array.

var data = [{ value: 'one', other: 'othervalue' }, { value: 'two' }, { value: 'three' }, { value: 'four' }],
    values = ['one', 'two', 'six', 'five', 'six'],
    hash = Object.create(null);

data.forEach(function (a) {
    hash[a.value] = true;
});

values.forEach(function (a) {
    if (!hash[a]) {
        hash[a] = true;
        data.push({ value: a });
    }
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Matt Burland
Matt Burland

Reputation: 45135

var original = [{'value':'one','other':'othervalue'},{value:'two'},{value:'three'},{value:'four'}];

var toAdd = ['one','two','six','five'];

// First make a dictionary out of your original array
// This will save time on lookups
var dictionary = original.reduce(function(p,c) {
      p[c.value] = c;
      return p;
  }, {});

// Now for each item in your new list
toAdd.forEach(function(i) {
  // check that it's not already in the dictionary
  if (!dictionary[i]) {
        // add it to the dictionary
        dictionary[i] = { value: i };
        // and to your original array
        original.push(dictionary[i]);
    }
  });

console.log(original);

Making the dictionary here I'm assuming the original doesn't have any duplicates to start with.

Upvotes: 1

Related Questions