javascript – Convert array Objects to array array with reduce

Question:

I have an array with object and I need to convert it into an array with n positions according to the data of the objects

let data: [ {cant: 1, producto: "ZAPATOS"},
            {cant: 9, producto: "CAMISAS"},
            {cant: 30, producto: "ZAPATOS"}
          ]

I need to convert it to

let datosFinales = [["ZAPATOS", 1, 30], ["CAMISAS", 9]]

I don't know if I'm getting complicated:

let serieX = ["ZAPATOS", "CAMISAS"];

let final = data.reduce((ant, actual, a) => {
  if (actual.servicio === serieX[0]) {
    if (ant.length > 0) {
      console.log("entro", ant);
      ant.push(actual.cant);
      return [ant];
    } else {
      ant.push(actual.producto);
      ant.push(actual.cant);
      return [ant];
    }
  }
  if (actual.servicio === serieX[1]) {
    let arraySerie = ant.filter(previo => previo === serieX[1]);
    if (arraySerie.length > 0) {
      arraySerie.push(actual.cant);
      ant.push(arraySerie);
      return [ant];
    } else {
      arraySerie.push(actual.producto);
      arraySerie.push(actual.cant);
      ant.push(arraySerie);
      return ant;
    }
  }
}, []);

Answer:

You can use Map , to save key, value, in the example the key would be the product and the values ​​would be the product plus their quantities! and finally convert them into an array with the Array.from function

 let data= [ {cant: 1, producto: "ZAPATOS"}, {cant: 9, producto: "CAMISAS"}, {cant: 30, producto: "ZAPATOS"} ] const grafico = new Map() for (let i = 0; i< data.length; i++){ let valor = grafico.get(data[i].producto) if(valor){ valor.push(data[i].cant) }else{ grafico.set(data[i].producto, [data[i].producto, data[i].cant]) } } const resultado_final = Array.from(grafico.values()) console.log(resultado_final)

The line valor.push(data[i].cant) have the same reference of the object so do not reassign it (array is of type object)

Scroll to Top