Home > Blockchain >  Increase count property on object if duplicate value exists in an array
Increase count property on object if duplicate value exists in an array

Time:12-21

I would like to take list variable and get it to the point that updated list is at but am unsure how.

const list = [{name:'apple'},{name:'apple'},{name:'banana'}];

const updatedList = [{name:'apple', count:2},{name:'banana', count: 1}];

CodePudding user response:

Maybe this example will help you ?

const list = [{name:'apple'},{name:'apple'},{name:'banana'}];

const updatedList = Object.values(list.reduce(
  (map, el) => {
    map[el.name] ? map[el.name].count   : map[el.name] = { ...el,
      count: 1
    };
    return map;
  }, {}
));
console.log(updatedList);

CodePudding user response:

function uptadeLi(list,item,quant) {
    // body...
    for( i in list){
        if (list[i].name === item){
            list[i].count = quant
        }
    }
}

With that function you can set each one of the elements of lists , be sure to put the name of item as string

CodePudding user response:

const list = [{name:'apple'},{name:'apple'},{name:'banana'}];
const res = list.reduce((sub,value)=>{
 const index= sub.findIndex(i => i.name===value.name)
    if(index !==-1)
    sub[index].count  
else
    sub.push({name:value.name,count:1})
return sub
},[])
console.log(res)

  • Related