1

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?

0

2 Answers 2

3

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)

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

Comments

1

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);

2 Comments

one thing I don't understand is this part: {letter,instances: numbers[i][j]} - why wouldn't it be {letter: letter,instances: numbers[i][j]}? how does your code know to assign letter as 'letter'?
It's object shorthand property names introduced in ES2015.

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.