Home > Software design >  Combine two arrays into an object in a specific way
Combine two arrays into an object in a specific way

Time:03-09

I need to get this combination from these two arrays like this.

const array1 = [ '0', '4', '8', '16', '24', '32', '40', '48', '56', '64' ]
const array2 = [ 'p', 'px', 'py', 'pt', 'pe', 'pb', 'ps', 'm', 'mx', 'my', 'mt', 'me', 'mb', 'ms']

// output
// const combine = {p: [p-0, p-4, p-8,...], px: [px-0, px-4, px-8,...].....}

// we can access values like this
// combine.p
// combine.px

CodePudding user response:

You could map the first array as key ad prewfix and get the values of the other array as postfix.

const
    array1 = [ '0', '4', '8', '16', '24', '32', '40', '48', '56', '64' ],
    array2 = [ 'p', 'px', 'py', 'pt', 'pe', 'pb', 'ps', 'm', 'mx', 'my', 'mt', 'me', 'mb', 'ms'],
    result = Object.fromEntries(array2.map(k => [k, array1.map(v => [k, v].join('-'))]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related