malen malen - 3 months ago 20
Javascript Question

Merge/flatten multidimensional array and remove duplicates Javascript

I have a multidimensional array that looks like this:

var workouts = [
[0, Object, 0, 0, 0],
[Object, 0, 0, 0, 0],
[0, 0, 0, Object, 0]
];


I'd like to flatten/merge the array and remove the duplicates. The result should look something like this:

[Object, Object, 0, Object, 0]


Is it possible to perform?

Answer

My understanding is that you want to keep the first encountered object in a given column if it exists.

You can do that with .map() and .reduce():

var workouts = [
  [0, {id:1}, 0, 0, 0],
  [{id:2}, 0, 0, 0, 0],
  [0, 0, 0, {id:3}, 0]
];

var res = workouts.reduce(function(a, b) {
  return b.map(function(e, i) { return a[i] instanceof Object ? a[i] : e; });
}, []);


console.log(JSON.stringify(res));

Comments