2
\$\begingroup\$

I have a bidimensional array like this:

const bArray = 
[ [ 'Hello World',
    'Hi everybody',
    'How are you?'
  ],
  [ { text: 'Hola Mundo',
      from: [Object],
      raw: '' },
    { text: 'Hola a todos',
      from: [Object],
      raw: '' },
    { text: 'Cómo estás?',
      from: [Object],
      raw: '' },
  ]
]

And I need to get as a result, only one array that should look like this:

[
 { en: 'Hello World',
   es: 'Hola Mundo' },

 { en: 'Hi everybody',
   es: 'Hola a todos' },

 { en: 'How are you?',
   es: 'Cómo estás?' },
]

This is how I do it:

let val1 = bArray[0].map(tuple => tuple);
let val2 = bArray[1].map(tuple => tuple);

let result = val1.reduce((arr, v, i) => arr.concat({"en" : v, "es" : val2[i].text}), []);

And now in the result variable, I have only one array with the result showed before.


My question?

Is there any improved way in which I can get the same result but with fewer lines of code? I mean, something like a combination of map with reduce, filter or concat in only one or two lines of code.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You can compact a lot into a single line, but that is most times not the best thing to do in both source code quality and execution efficiency.

const bArray = [['Hello World', 'Hi everybody', 'How are you?'], [{ text: 'Hola Mundo', from: [Object],  raw: '' }, { text: 'Hola a todos',   from: [Object], raw: '' }, { text: 'Cómo estás?',  from: [Object],  raw: '' },]];

const resultArray = bArray[0].reduce((arr, item, i) => (arr.push({en : item, es : bArray[1][i].text}), arr), []);
console.log(resultArray);

However I would do it as follows.

const bArray = [['Hello World', 'Hi everybody', 'How are you?'], [{ text: 'Hola Mundo', from: [Object],  raw: '' }, { text: 'Hola a todos',   from: [Object], raw: '' }, { text: 'Cómo estás?',  from: [Object],  raw: '' },] ];

const result = [], aArr = bArray[0];
var i = 0;
for (const item of bArray[1]) { result.push({es : item.text, en : aArr[i++]}) }

console.log(result);

Which is easier to read and quicker when run.

Expanding it to idiomatic JS style.

const result = [];
let i = 0;
for (const en of bArray[0]) { 
    result.push({
        en, 
        es : bArray[1][i++].text
    });
}

// or
const result = [];
let i = 0;
for (const item of bArray[1]) { 
    result.push({
        es : item.text,
        en : bArray[0][i++]
    });
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ In the last example, you need to fix en : bArray[i++] to en : bArray[0][i++] to get it work. \$\endgroup\$
    – robe007
    May 24, 2018 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.