Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
No está definido en el resultado del mapa

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: 68

aunque, el resultado que quiero es así

 0: key: "Harry Potter" link: "https://harry-potter" value: 220 1: key: "Naruto" link: "https://naruto" value: 68
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Map.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);

about 4 years ago · Juan Pablo Isaza Report

0

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))

about 4 years ago · Juan Pablo Isaza Report

0

Lo resolvería con un Array.reduce así:

  1. Primero inicializaría el valor que reduce va a volver a una matriz vacía.

  2. Luego verificaría si el artículo ya existe en el acumulador.

    1. Si no existe , simplemente devuelvo una nueva matriz, con los elementos anteriores en la matriz y el valor de iteración actual.

    2. 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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!