Filter JS array based on same values in a sequence [closed]

I’ve an array like this.

const cars = [
  {year: "2003", made: "BMW"},
  {year: "2004", made: "Honda"},
  {year: "2005", made: "BMW"},
  {year: "2006", made: "BMW"},
  {year: "2006", made: "Mercedes"},
  {year: "2007", made: "BMW"},
  {year: "2008", made: "Mercedes"},
  {year: "2009", made: "Mercedes"},
];

An expected output:

const output = [
  [
    {year: "2003", made: "BMW"},
  ],
  [
    {year: "2004", made: "Honda"},
  ],
  [
    {year: "2005", made: "BMW"},
    {year: "2006", made: "BMW"},
  ],
  [
    {year: "2006", made: "Mercedes"},
  ],
  [
    {year: "2007", made: "BMW"},
  ].
  [
    {year: "2008", made: "Mercedes"},
    {year: "2009", made: "Mercedes"},
  ],
];

I hope the requirements are already clear from above code snippets. The main idea is to create an array object or multi dimensional array from the existing data based on matching value of a key. In example above the made key is filtered.

Answer

Use reduce and check if the previous made is equal to the current made then add to the same index or else push to the result

const cars = [
    {year: '2003', made: 'BMW'},
    {year: '2004', made: 'Honda'},
    {year: '2005', made: 'BMW'},
    {year: '2006', made: 'BMW'},
    {year: '2006', made: 'Mercedes'},
    {year: '2007', made: 'BMW'},
    {year: '2008', made: 'Mercedes'},
    {year: '2009', made: 'Mercedes'},
];


let carsResult = [];
cars.reduce((prev, curr) => {
  if (curr.made != prev.made) {
    carsResult.push([curr])
  } else {
    carsResult[carsResult.length - 1].push(curr)
  }
  return curr
}, {})
console.log(carsResult)

Leave a Reply

Your email address will not be published. Required fields are marked *