Skip to content
Advertisement

Create a function to sort the array of objects by three specific keys

I have the array of objects: the cars with the data. And I have a given sorted array of objects – these cars sorted by colors (red, black, other) and nested inside. Here you can take a look: JSFiddle – Two Arrays, unsorted and sorted

Which array method is better to use to create something like that? And I wouldn’t like to mutate the given array.

    const unsortedCars = [
    {
        id: 3,
        seller: 'Anna',
        dataPublished: 'date',
        carData: {
            id: 3,
            color: 'red',
            is_sport: false,
        },
    },
    {...},
];

const sortedCarsByColors = [
    {
        color: 'red',
        cars: [
            {
                id: 3,
                seller: 'Anna',
                dataPublished: 'date',
                carData: {
                    id: 3,
                    color: 'red',
                    is_sport: false,
                },
            },
            {...},
        ],
    },
];

Advertisement

Answer

“group by array of objects using reduce”

const unsortedCars = [{
    id: 3,
    seller: 'Anna',
    dataPublished: 'date',
    carData: {
      id: 3,
      color: 'red',
      is_sport: false,
    },
  },
  {
    id: 2,
    seller: 'Mark',
    dataPublished: 'date',
    carData: {
      id: 2,
      color: 'black',
      is_sport: false,
    },
  },
  {
    id: 3,
    seller: 'Anna',
    dataPublished: 'date',
    carData: {
      id: 3,
      color: 'red',
      is_sport: false,
    },
  },
  {
    id: 4,
    seller: 'Richard',
    dataPublished: 'date',
    carData: {
      id: 4,
      color: 'blue', // nor red or black
      is_sport: false,
    },
  },
];

var obj = unsortedCars.reduce(function(agg, item) {
  var color = item.carData.color;
  if (color != "red" && color != "black") {
    color = "other";
  }
  agg[color] = agg[color] || {
    color: color,
    cars: []
  }
  agg[color].cars.push(item)
  return agg;
}, {});

console.log(Object.values(obj))
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement