Tengo problemas para convertir, sumar y ordenar las siguientes matrices en objetos clave y de valor
matriz de datos
0: {No: '1', Product Name: 'Harry Potter', Type: 'Novel', Price: '120', Url: 'https://harry-potter'} 1: {No: '2', Product Name: 'Harry Potter', Type: 'Novel', Price: '100', Url: 'https://harry-potter'} 2: {No: '3', Product Name: 'Naruto', Type: 'Comic', Price: '68', Url: 'https://naruto'} n: {No: '...', Product Name: '...', Type: '...', Price: '...', Url: '...'}mi código actual
let counts = myRows.reduce((prev, curr) => { let count = prev.get(curr["Product Name"]) || 0; prev.set( curr["Product Name"], parseFloat(curr["Product Name"]) + count, curr["Url"] ); return prev; }, new Map()); // then, map your counts object back to an array let reducedObjArr = [...counts].map(([key, value, link]) => { return { key, value, link }; }); // SORT BY DESCENDING VALUE var desc = reducedObjArr.sort((a, b) => b.value - a.value); console.log(desc);y el resultado de mi código actual
0: key: "Harry Potter" link: undefined value: 220 1: key: "Naruto" link: undefined value: 68aunque, el resultado que quiero es así
0: key: "Harry Potter" link: "https://harry-potter" value: 220 1: key: "Naruto" link: "https://naruto" value: 68Map.prototype.set() solo toma 2 argumentos, está pasando 3. Si desea almacenar múltiples valores en una clave de mapa, guárdelos como una matriz u objeto. En mi código a continuación, almaceno [price, url] .
Otro problema es que intentaba analizar curr["Product Name"] como el precio, pero debería ser curr.Price .
const myRows = [ {No: '1', "Product Name": 'Harry Potter', Type: 'Novel', Price: '120', Url: 'https://harry-potter'}, {No: '2', "Product Name": 'Harry Potter', Type: 'Novel', Price: '100', Url: 'https://harry-potter'}, {No: '3', "Product Name": 'Naruto', Type: 'Comic', Price: '68', Url: 'https://naruto'} ]; let counts = myRows.reduce((prev, curr) => { let count = prev.get(curr["Product Name"])?.[0] || 0; prev.set( curr["Product Name"], [parseFloat(curr.Price) + count, curr.Url ] ); return prev; }, new Map()); // then, map your counts object back to an array let reducedObjArr = [...counts].map(([key, [value, link]]) => { return { key, value, link }; }); // SORT BY DESCENDING VALUE var desc = reducedObjArr.sort((a, b) => b.value - a.value); console.log(desc);Como alternativa a Map , también podría crear un objeto JS usando reduce() y, al final, use Object.values() para obtener los valores como una matriz.
const data = [ { No: "1", "Product Name": "Harry Potter", Type: "Novel", Price: "120", Url: "https://harry-potter", }, { No: "2", "Product Name": "Harry Potter", Type: "Novel", Price: "100", Url: "https://harry-potter", }, { No: "3", "Product Name": "Naruto", Type: "Comic", Price: "68", Url: "https://naruto", }, ]; const result = data.reduce((prev, movie) => { // destruct properties for convenience to have shorter name const { "Product Name": key, Url: link, Price: value } = movie; // parse the value const floatValue = parseFloat(value) || 0; // use previous value to compute new accumulated value if there is a previous value const accValue = prev[key] ? prev[key].value + floatValue: floatValue; // set and return new value prev[key] = {key: key, link: link, value: accValue}; return prev; }, {}) console.log(Object.values(result))Lo resolvería con un Array.reduce así:
Primero inicializaría el valor que reduce va a volver a una matriz vacía.
Luego verificaría si el artículo ya existe en el acumulador.
Si no existe , simplemente devuelvo una nueva matriz, con los elementos anteriores en la matriz y el valor de iteración actual.
Si existe , itero el acumulador con el mapa para devolver una nueva matriz, vuelvo y verifico que el objeto existe, si existe, agrego la cantidad actual de la iteración del mapa a la cantidad actual de la iteración de reducción, si no existe. t existe, solo devuelvo el valor actual de la iteración dentro del mapa.
let myRows = [ { No: 1, "Product Name": 'Harry Potter', Type: 'Novel', Price: '120', Url: 'https://harry-potter' }, { No: 2, "Product Name": 'Harry Potter', Type: 'Novel', Price: '100', Url: 'https://harry-potter'}, { No: 3, "Product Name": 'Naruto', Type: 'Comic', Price: '68', Url: 'https://naruto' } ]; const counts = myRows.reduce((accumulator, currentValue) => { const elementAlreadyExists = accumulator.find(element => element["Product Name"] === currentValue["Product Name"]); if (elementAlreadyExists) { return accumulator.map((element) => { if (element["Product Name"] === currentValue["Product Name"]) { return { ...element, Price: parseFloat(element.Price) + parseFloat(currentValue.Price) } } return element; }); } return [...accumulator, currentValue]; }, []); console.log(counts);