-1

I have two arrays with the same number of elements which maps 1:1

const array1 = [1, 3, 2]
const array2 = [U2, U1, U3]

How can I generate a new array (or map) from array1 & array2 and have something like this ?

const result = [[1, U1], [2, U2], [3, U3]]
user3574857
  • 377
  • 4
  • 16

2 Answers2

3

You can also use Array.forEach(). Before that you can sort the array1 array and then get the corresponding value from array2 prefixed with U to get the desired output:

const array1 = [1, 3, 2];
const array2 = ['U2', 'U1', 'U3'];
const result = [];
array1.sort(function(a,b){
  return a-b;
})
array1.forEach((elem, index) => result.push([elem, array2[array2.indexOf('U'+elem)]]));
console.log(result);

If the prefix is not always U then this can be used:

const array1 = [1, 3, 2];
const array2 = ['U2', 'U1', 'U3'];
const result = [];
array1.sort(function(a,b){
  return a-b;
})
array1.forEach((elem) => {
  var array2Val = array2.find(val => val.indexOf(elem) !== -1);
  result.push([elem, array2Val]);
});
console.log(result);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

You could group the arrays by the numerical value of each item.

var array1 = [1, 3, 2],
    array2 = ['U2', 'U1', 'U3'],
    result = Object.values([array1, array2].reduce(
        (o, a) => {
            a.forEach(v => {
                var k = v.toString().match(/\d+$/)[0];
                (o[k] = o[k] || []).push(v);
            });
            return o;
        },
        Object.create(null)
    ));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392