Skip to content
Advertisement

Use an object attribute to create an array with it [closed]

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

Advertisement

Answer

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 }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement