3

I have array like this

   var arr = [
                [ {"c": 1},{"d": 2} ],
                [ {"c": 2},{"d": 3} ]
             ]

I want to change into (by javascript only)

var newArr  = [{"c": 1},{"d": 2},{"c": 2},{"d": 3}]

I have tried this by map but not getting expected output .

4
  • Please show us what you've tried (your try with map)
    – Sebastian
    Commented Feb 16, 2017 at 8:46
  • you want to flatten the array of arrays into a single array
    – Denis Tsoi
    Commented Feb 16, 2017 at 8:46
  • stackoverflow.com/questions/10865025/… [duplicate]
    – Denis Tsoi
    Commented Feb 16, 2017 at 8:47
  • with a recursive function, testing if isArray the element of a array Commented Feb 16, 2017 at 8:47

3 Answers 3

10

You can use reduce() and spread syntax.

 var arr = [
  [ {"c": 1},{"d": 2} ],
  [ {"c": 2},{"d": 3} ]
]

var result = arr.reduce((r, e) => (r.push(...e), r), [])
console.log(result)

1
  • I wish I could upvote this more than once, beautiful answer! Commented Feb 16, 2017 at 8:50
2

You could use Array#reduce with Array#concat.

var arr = [[{ c: 1 }, { d: 2 }], [{ c: 2 }, { d: 3 }]],
    result = arr.reduce((r, a) => r.concat(a), []);

console.log(result)

ES5

var arr = [[{ c: 1 }, { d: 2 }], [{ c: 2 }, { d: 3 }]],
    result = arr.reduce(function (r, a) { return r.concat(a); }, []);

console.log(result)

1

In plain JavaScript you can do this using Array.portotype.forEach.

var arr = [
                [ {"c": 1},{"d": 2} ],
                [ {"c": 2},{"d": 3} ]
             ];
             
var newArray = [];

arr.forEach(function(e){
	e.forEach(function(e1){
		newArray.push(e1);
	});
})

console.log(newArray);

Use this..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.