Skip to content

Instantly share code, notes, and snippets.

@NaokiStark
Created November 4, 2017 01:56
Show Gist options
  • Save NaokiStark/39fa6c2839eb3a14805b9d81631340c4 to your computer and use it in GitHub Desktop.
Save NaokiStark/39fa6c2839eb3a14805b9d81631340c4 to your computer and use it in GitHub Desktop.
var newProductos = [];
var Productos = [
{name: "usb", value:"5"},
{name: "usb", value:"10"},
{name: "pendriver", value:"50"},
{name: "pendriver", value:"5"},
{name: "usb", value:"3"}
];
//Loop entre productos
for(let a = 0; a < Productos.length; a++){
//El nombre del producto
let product = Productos[a].name;
//Buscar el producto si está listado en newProductos, sino = undefined
let listed = newProductos.find(function(elm){
return elm.name === product;
});
if(listed != undefined){
//Listado, sumamos
let i = newProductos.indexOf(listed);
newProductos[i].value = parseInt(newProductos[i].value) + parseInt(Productos[a].value);
}
else{
//No listado, agregamos
newProductos.push(Productos[a]);
}
}
console.log(newProductos); //[{"name":"usb","value":18},{"name":"pendriver","value":55}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment