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

154
Views
Use an object attribute to create an array with it

Hi guys i want to do something "simple" but not for me, I have this array

[
  { x: 'bmw', vehicule_type: car, y: 1 },
  { x: 'mercedes', vehicule_type: car, y: 2 },
  { x: 'airbus', vehicule_type: plane, y: 1 }
]

And i want to transform it to this thing

[
  car : [{ x: 'bmw',  y: 1 },  { x: 'mercedes', y: 1 }]
  plane: [{ x: 'airbus',  y: 1 }]
] 

I cant find a way to do it, i saw that i could use "reducer()" but for the rest i'm lost

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

0

Presented below is one possible way to achieve the desired objective.

Code Snippet

const myTransform = arr => (
  arr.reduce(
    (acc, {vehicule_type, ...rest}) => (
      (acc[vehicule_type] ??= []).push({...rest}),
      acc
    ),
    {}
  )
);

/* EXPLANATION of the code

// method to transform the array
const myTransform = arr => (
  arr.reduce(         // iterate using ".reduce()" with "acc" as accumulator
    // destructure the iterator to acces "vehicule_type"
    (acc, {vehicule_type, ...rest}) => (
      // if "acc" doesn't have "vehicule_type", set it as empty array
      // and then, push "rest" (ie, x, y, other props, if any) into the array
      (acc[vehicule_type] ??= []).push({...rest}),
      // implicit return of "acc"
      acc
    ),
    {}      // initialize "acc" as an empty object
  )
);

*/

const dataArr = [
  { x: 'bmw', vehicule_type: 'car', y: 1 },
  { x: 'mercedes', vehicule_type: 'car', y: 2 },
  { x: 'airbus', vehicule_type: 'plane', y: 1 }
];

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

Explanation

Inline comments added to the snippet above.

EDIT

As noted by Bergi in a comment below, an alternative using for loop is also possible. This may look something as shown below:

const myTransform = arr => {
  const res = {};
  for (const {vehicule_type, ...rest} of dataArr) {
    (res[vehicule_type] ??= []).push({...rest});
  };
  return res;
};

/* EXPLANATION
// alternative method to transform the array
const myTransform = arr => {
  // set up result "res" as an empty object "{}"
  const res = {};
  // iterate over elts of "dataArr"
  // destructure the iterator to directly access "vehicule_type"
  for (const {vehicule_type, ...rest} of dataArr) {
    // if "vehicule_type" not already in "res", 
    // then, set it with a value of empty array
    // push the remaining props "...rest" into the array
    (res[vehicule_type] ??= []).push({...rest});
  };
  // return the result
  return res;
};
*/

const dataArr = [
  { x: 'bmw', vehicule_type: 'car', y: 1 },
  { x: 'mercedes', vehicule_type: 'car', y: 2 },
  { x: 'airbus', vehicule_type: 'plane', y: 1 }
];

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

about 4 years ago · Juan Pablo Isaza Report

0

You can group the data by vehicle_type using Array.prototype.reduce.

const 
  data = [
    { x: "bmw", vehicle_type: "car", y: 1 },
    { x: "mercedes", vehicle_type: "car", y: 2 },
    { x: "airbus", vehicle_type: "plane", y: 1 },
  ],
  result = data.reduce(
    (r, { vehicle_type: t, ...o }) => ((r[t] ??= []).push(o), r),
    {}
  );

console.log(result);

If you're finding it difficult to understand the above solution, refer to this more descriptive version:

const 
  data = [
    { x: "bmw", vehicle_type: "car", y: 1 },
    { x: "mercedes", vehicle_type: "car", y: 2 },
    { x: "airbus", vehicle_type: "plane", y: 1 },
  ],
  result = data.reduce((r, { vehicle_type: t, ...o }) => {
    if (!r[t]) {
      r[t] = [];
    }
    r[t].push(o);
    return r;
  }, {});

console.log(result);

Relevant documentations:

  • Nullish coalescing operator (??)
  • Rest parameters
  • Object destructuring
  • Comma operator (,)
about 4 years ago · Juan Pablo Isaza Report

0

I'm not sure whether this is the best way to do this; probably not, but this is what I came up with..

let array = [{
    x: 'bmw',
    vehicle_type: "car",
    y: 1
  },
  {
    x: 'mercedes',
    vehicle_type: "car",
    y: 2
  },
  {
    x: 'airbus',
    vehicle_type: 'plane',
    y: 1
  },
  {
    x: 'mercedes',
    vehicle_type: "car",
    y: 2
  }
]

function sortByType(array) {
  const vehicles = {};
  for (let object of array) {
    let vehicle = {},
      type = undefined;
    for (let property in object) {
      if (type === undefined) type = object["vehicle_type"];
      if (vehicles[type] === undefined) vehicles[type] = [];
      if (property === "vehicle_type") continue;

      vehicle[property] = object[property];
    }
    vehicles[type].push(vehicle);
  }
  return vehicles
}

const vehicles = sortByType(array)
console.log(vehicles)

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!