I have two arrays're contained objects and i need to put elements(objects) to first array How to do that ? mybe with underscore?
            Asked
            
        
        
            Active
            
        
            Viewed 37 times
        
    -2
            
            
        - 
                    please add some data and the code you tried. – Nina Scholz Feb 08 '16 at 09:30
- 
                    Possible duplicate of [How to merge two arrays in Javascript and de-duplicate items](http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Alexander Elgin Feb 08 '16 at 09:37
3 Answers
3
            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.push(arr1)
arr = _.flatten(arr)
 
    
    
        Cyril Cherian
        
- 32,177
- 7
- 46
- 55
1
            
            
        underscore / lodash is not required
var numbers = [1, 2, 3];
var letters = ['a', 'b', 'c'];
var numbers = numbers.concat(letters);
document.write(JSON.stringify(numbers)); 
    
    
        Alexander Elgin
        
- 6,796
- 4
- 40
- 50
0
            
            
        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}
]
 
    
    
        Shubham Dubey
        
- 118
- 3
