I want to update he array based on id with some conditions. Conditions were =
const data1 = [
{ type:"foo", id:"123"},
{ type:"bar", id:"124"},
]
const update1 = {type:"bar",id:"123"}
const update2 = {type:"foo", id:"125"}
const update3 = {type:"bar", id:"123"}
console.log(myupdate(data1, update1))
should update the data1 as bellow based on id here the type is changed to bar
data1 = [ { type:"bar", id:"123"},
{ type:"bar", id:"124"}, ]
console.log(myupdate(data1, update2))
here as no item with id 125 exist so it adds a new one
data1 = [ { type:"bar", id:"123"},
{ type:"bar", id:"124"},
{ type:"foo", id:"125"} ]
console.log(myupdate(data1, update3))
here type is not changed so it should return the array as it is.
data1 = [{ type:"bar", id:"123"},
{ type:"bar", id:"124"},
{ type:"foo", id:"125"}
]
I have tried this code but it doesn't work
const myupdate = (arr, element) => {
arr.map((item)=>{
console.log(item, "ele",element)
if(item.id != element.id){
arr.push(element)
return
}
if(item.id === element.id && item.type === element.type){
return
}
if(item.id === element.id && item.type != element.type){
arr.filter(item => item !== element).push(element)
return
}
})
}
console.log()will always logundefined(the default return value of a function). You are also mutating the array passed as a parameter rather than returning a new array.