Home Ask Login Register

Developers Planet

Your answer is one click away!

Decastrio February 2016

oneArray's objects + twoAarray's objects to and of oneArray

I have two arrays're contained objects and i need to put elements(objects) to first array How to do that ? mybe with underscore?


Cyril February 2016

Plain JS:

arr = [1,2,3,4]
arr1 = [6,7]
arr = arr.concat(arr1)

Using underscore

arr = [1,2,3,4]
arr1 = [6,7]

arr = _.flatten(arr)

Alexander Elgin February 2016

underscore / lodash is not required

var numbers = [1, 2, 3];
var letters = ['a', 'b', 'c'];
var numbers = numbers.concat(letters);


Shubham Dubey February 2016

If you want to merge two array contaning objects, you have to choose field of object by which you want to merge.

array1 = [
 {field: 'username', display: 'username', hide: true},
 {field: 'age', display: 'Age', hide: true},
 {field: 'height', display: 'Height', hide: true}

array2 = [
{field: 'username', display: 'username 123', hide: false},
{field: 'age', hide: false}

Underscore -function-

_.values(_.extend(_.indexBy(array1, 'field'), _.indexBy(array2, 'field')))

We use indexBy to turn the arrays into objects keyed on the field value, and then extend does what we want. Finally, values turns it back into an array.

result -

 array3 = [
{field: 'username', display: 'username 123', hide: false},
{field: 'age', display: 'Age', hide: false},
{field: 'height', display: 'Height', hide: true}

Post Status

Asked in February 2016
Viewed 3,211 times
Voted 5
Answered 3 times


Leave an answer

Quote of the day: live life