You are on a right way, but you are not using Array.filter
properly.
And also the provided array of object is not also in a good format. Object should be in a key:value
pairs.
state.products = [
{ id: 1, name: "Bottle" },
{ id: 2, name: "umbrella" },
{ id: 3, name: "shoe" }
]
const getAllArrayExcept = (id) => {
// this will return all the array except provided id
return state.products.filter((s) => s.id !== id)
}
const getOnlyArray = (id) => {
// this will return only item which match the provided id
return state.products.filter((s) => s.id === id)
}
console.log(getAllArrayExcept(1))
/*
output: [{ id = 2, name = umbrella }, { id = 3, name = shoe }]
*/
console.log(getOnlyArray(1))
/*
output: [{ id = 1, name = Bottle }]
*/
Here is the working snippet:
const products = [
{ id: 1, name: "Bottle" },
{ id: 2, name: "umbrella" },
{ id: 3, name: "shoe" }
]
const getAllArrayExcept = (id) => {
// this will return all the array except provided id
return products.filter((s) => s.id !== id)
}
const getOnlyArray = (id) => {
// this will return only item which match the provided id
return products.filter((s) => s.id === id)
}
console.log("All array except: ", getAllArrayExcept(1))
console.log("Only provided item in array: ", getOnlyArray(1))