2

I have a source multidimensional array. It looks like:

var arr = [];
arr[1] = [];
arr[2] = [];
arr[3] = [];
arr[1][1] = "11";
arr[1][2] = "12";
arr[1][3] = "13";
arr[2][1] = "21";
arr[2][2] = "22";
arr[2][3] = "23";
arr[3][1] = "31";
arr[3][2] = "32";
arr[3][3] = "33";

I need to convert this to a flat array using ES6 features. Result must looks like this:

var res = [
  { col:1, row:1, val:"11"},
  { col:1, row:2, val:"12"},
  { col:1, row:3, val:"13"},
  { col:2, row:1, val:"21"},
  { col:2, row:2, val:"22"},
  { col:2, row:3, val:"23"},
  { col:3, row:1, val:"31"},
  { col:3, row:2, val:"32"},
  { col:3, row:3, val:"33"}
];
2
  • why starting indexes are 1? Commented Mar 2, 2017 at 11:50
  • 1
    the second piece of code, isn't a valid js, if you meant Object you should replace = with : Commented Mar 2, 2017 at 11:51

1 Answer 1

6

You could use Array#reduce and Array#forEach for new objects.

var arr = [, [, '11', '12', '13'], [, '21', '22', '23'], [, '31', '32', '33']],
    result = arr.reduce((r, a, col) => (a.forEach((val, row) => r.push({ col, row, val })), r), []);

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.