I have a sample array bunch as
let bunch = [{fruit: "apple" , quantity: 1},{fruit: "banana" , quantity: 3}]
I am trying to split the object to its quantity times --> if fruit is banana and quantity > 1 as:
//newBunch --> [{fruit: "apple" , quantity: 1},{fruit: "banana" , quantity: 1},{fruit: "banana" , quantity: 1},{fruit: "banana" , quantity: 1}]
I have tried using reduce as :
let bunch = [{fruit: "apple" , quantity: 1},{fruit: "banana" , quantity: 3}]
let res = bunch.reduce((acc,curr)=>{
if(curr.quantity > 1 && curr.fruit==='banana'){
var arr = []
for(let i=0; i < curr.quantity ; i++){
var fr = {}
fr.fruit = 'banana';
fr.quantity = 1;
arr.push(fr)
}
acc.push(...arr)
}
else{
acc.push(curr)
}
return acc
},[])
console.log(res)
I get the expected o/p using above snippet , but there would be an efficient way to do this (less code probably ) or would you just suggest to go with the current solution? please guide me along this. TIA