Home > Back-end >  how to create 2 arrays by running once on an array containing objects with the arrays matching the f
how to create 2 arrays by running once on an array containing objects with the arrays matching the f

Time:10-24

for example - lets say I have the array -

const array = [{name: "first", val: 1}, {name: "second", val: 2}]

I want to run once on that array and at the end of that run to have two arrays -

const arrayOne = ["first", "second"]; const arrayTwo = [1,2];

to get the first one is easy, but getting both at once?

I remember there was a way to do it but couldn't find it..

I'd appreciate any help!

CodePudding user response:

Any looping logic will help

Array.reduce implementation will be like below

const array = [{ name: "first", val: 1 }, { name: "second", val: 2 }];
const [arrayOne, arrayTwo] = array.reduce((acc, curr) => {
  const { name, val } = curr;
  acc[0].push(name);
  acc[1].push(val);
  return acc;
}, [[], []]);
console.log(arrayOne, arrayTwo);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The function extractArrays is general-purpose and can be used in other cases as well.

function extractArrays(arr) {
  const result = {};
  for (obj of arr) {
    for (key in obj) {
      result[key] = (result[key] || []).concat([obj[key]]);
    }
  }
  return result;
}

const array = [{name: "first", val: 1}, {name: "second", val: 2}];
const result = extractArrays(array);
const arrayOne = result.name;
const arrayTwo = result.val;

console.log(`arrayOne=${arrayOne}`);
console.log(`arrayTwo=${arrayTwo}`);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use Array.reduce to achieve this:

const array = [{name: "first", val: 1}, {name: "second", val: 2}]

const result = array.reduce((res, item) => {
  res[0].push(item.name)
  res[1].push(item.val)
  return res
}, [[], []])

console.log(result)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related