Home > Software design >  Create new array object value from two different array with equal length in JavaScript
Create new array object value from two different array with equal length in JavaScript

Time:11-06

Need to create new array object from two other arrays in JS

var array1 = ['one', 'two', 'one, 'two'];
var array2 = ['3', '4', '5', '6'];

Here array1[0] = one represents array2[0] = 3 and vice versa.

Need to create a new array object with array1's value as its key and array2's value as its value

Output needed

var arrayObj = {"one": [{"0":"3", "1":5} ],"two": [{"0":"4", "1":6}]}

Here 3 and 5 in array2 should push to index "one" and 4 and 6 in array2 should push to index "two" ?

CodePudding user response:

Maybe I am mistaken, but it seems to me that OP wants something like this:

function map2(a1,a2){
  return a1.reduce((a,c,i)=>{
   (a[c]??=[]).push(a2[i]);
   return a;
  },{})
}
const
  array1 = ['one', 'two', 'one', 'two'],
  array2 = ['3', '4', '5', '6'];
    
console.log(map2(array1,array2));

CodePudding user response:

Take an object and collect the value and build a new object with the wanted structure.

const
    combine = (a, b) => {
        const temp = {};
        for (let i = 0; i < array1.length; i  ) (temp[a[i]] ??= []).push(b[i]);
        return temp;
    },
    array1 = ['one', 'two', 'one', 'two'],
    array2 = ['3', '4', '5', '6'],
    result = Object.fromEntries(Object
        .entries(combine(array1, array2))
        .map(([k, a]) => [k, Object.assign({}, a)])
    );

console.log(result);

  • Related