Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
how to create 2 arrays by running once on an array containing objects with the arrays matching the fields?

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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}`);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!