user8758206
user8758206

Reputation: 2191

Merging two Multidimensional Arrays into a Multidimensional Array with Objects

I'm learning the new JavaScript ES6 syntax and am trying to create a multidimensional array with objects from 2 other multidimensional arrays. Presumably my syntax is incorrect, but I don't know how to fix it. The result should be:

[
  [{    letter: w,    instances: 1
  }, {  letter: o,    instances: 1
  }, {  letter: d,    instances: 2
  }, {  letter: r,    instances: 1
  }],
  [{    letter: s,    instances: 1
  }, {  letter: y,    instances: 1
  }],
  [{    letter: h,    instances: 1
  }, {  letter: e,    instances: 1
  }, {  letter: l,    instances: 2
  }, {  letter: o,    instances: 1
  }]
]

My code uses two map methods:

var letters = [
  ["w", "o", "d", "r"],
  ["s", "y"],
  ["h", "e", "l", "o"]
];
var numbers = [
  [1, 1, 2, 1],
  [1, 1][1, 1, 2, 1]
];
var objArr = letters.map(function(c, i) {
  return c.map(function(c2, i2, a2) {
    return {
      letter: c2,
      instances: numbers[i]
    }
  })
});
console.log(objArr);

It correctly returns a multidimensional array with objects and correct letter values, but the number values are incorrect. Can anyone find why this happens? Also, does anyone think there's a better way of storing the letters and the number of numbers?

Upvotes: 1

Views: 143

Answers (2)

Hassan Imam
Hassan Imam

Reputation: 22534

Since you have a two-dimensional array, you need to use two indexes to access it. Use the first index i, to access the inner array and the use second index j, to access the number inside the array.

let letters = [["w", "o", "d", "r"],["s", "y"],["h", "e", "l", "o"]],
    numbers = [[1, 1, 2, 1],[1, 1],[1, 1, 2, 1]],
    result = letters.map((arr, i) => arr.map((letter, j) => ({letter,instances: numbers[i][j]})));
console.log(result);

Upvotes: 1

Nitish Narang
Nitish Narang

Reputation: 4184

One very small mistake in instances: Pls see below

var letters = [["w", "o", "d", "r"],["s", "y"],["h", "e", "l", "o"]];

var numbers = [[1,1,2,1],[1,1], [1,1,2,1]];

var objArr = letters.map(function(c,i) {
                return c.map(function(c2,i2) {
                    return {letter: c2, instances: numbers[i][i2]}
                })
            });

console.log(objArr)

Upvotes: 3

Related Questions