Reputation: 606
I have an array of objects and I want to check whether a given object is present in the array and if yes,I want to delete that,If not I have to add it to the array.
I am doing this:
var arr=[
{
name: "Jack",
type: "Jill",
},
{
name: "Heer",
type: "Ranjha",
},
{
name: "laila",
type: "Majnu",
};
]
var tosearch = {
name: "Jack",
type: "Jill",
};
if(arr.includes(tosearch))
{
//I want to delete it from the arr.
}
else
arr.push(tosearch)
How can I achieve the above implementation?
Thanks
Upvotes: 2
Views: 86
Reputation: 14363
You can use Array.prototype.filter
to achieve filtering:
/** utils.js */
// default options can be set, here we will create search filter which pick from id
const defaultSearchFilterOptions = { key: 'id', pick: true }
/**
* @description
* factory to create array filter utilities
* @params {object} [options={}] - options used to generate the new filter
* @params {string} [options.key='id'] - key used for comparing
* @params {boolean} [options.pick=true] - inverse the filter (with/without)
* @params {string} options.search - exact match to search (can be improved with a regex or whatever etc..
* @returns {function} filter - function that can be used with `Array.prototype.filter`
*/
function createSearchFilter(options = {}) {
// apply user's options on top of default options, user MUST pass at least "search" options
const { key, search, pick } = { ...defaultSearchFilterOptions, ...options }
// return a filter function, based on computed options
return (item) => pick ? item[key] === search : item[key] !== search
}
/** app.js */
// data
var arr = [
{
name: "Jack",
type: "Jill",
},
{
name: "Heer",
type: "Ranjha",
},
{
name: "laila",
type: "Majnu",
}
];
// using factory, create a filter on name where value is "jack"
const filterInJack = createSearchFilter({
key: 'name',
search: 'Jack',
});
// using factory, create a filter on name where value is not "jack"
const filterOutJack = createSearchFilter({
key: 'name',
search: 'Jack',
pick: false,
});
/** Results */
console.log(arr.filter(filterInJack));
console.log(arr.filter(filterOutJack));
Source: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Upvotes: 2
Reputation: 891
If the number of properties are fixed(in your case its 2 name
and type
) and you know them before running then you can simply use this.
This approach may not be an ideal one but if the data is of this type then i guess this might be might be a good and easy to understand approach
//here i is the index of a object in arr
if(arr[i].name == tosearch.name && arr[i].type == tosearch.type) {
//delete it
} else {
arr.push(tosearch);
}
Upvotes: 1
Reputation: 202676
Array.prototype.includes
only works for primitives and object via shallow reference equality, i.e. if they are the same object in memory.
Create a utility to check if the array contains some element where every property of the "search" object is equal.
const arrayContainsObject = (array, object) =>
array.findIndex((el) =>
Object.entries(object).every(([key, value]) => el[key] === value)
);
This example returns the index of the element if found, otherwise it returns -1
.
You can use this to either filter the element from the array or append it.
let result;
const index = arrayContainsObject(arr, toSearch);
if (index !== -1) {
result = arr.filter((el, i) => i !== index);
} else {
result = arr.concat(toSearch);
}
const arr = [
{
name: "Jack",
type: "Jill"
},
{
name: "Heer",
type: "Ranjha"
},
{
name: "laila",
type: "Majnu"
}
];
const toSearch = {
name: "Jack",
type: "Jill"
};
const arrayContainsObject = (array, object) =>
array.findIndex((el) =>
Object.entries(object).every(([key, value]) => el[key] === value)
);
let result;
const index = arrayContainsObject(arr, toSearch);
if (index !== -1) {
result = arr.filter((el, i) => i !== index);
} else {
result = arr.concat(toSearch);
}
console.log(result);
Upvotes: 2
Reputation: 1077
You can use this code
arr = arr.filter(item => item !== tosearch)
but, there is better way for handle this you can add an id field for each object and wherever you want to check and find specific item you can use that id
arr = arr.filter(item => item.id !== tosearch.id)
Upvotes: 4
Reputation: 873
Deleting an element from an array using filter. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
const newArray = existingArray.filter(element => element.id != deleteId);
Searching I usually use a simple findIndex. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
const doesElementExist = arr.findIndex(element => element.id === selectedId);
if (doesElementExist > 0) { // Delete element }
This relies on you having a unique identifier in the object potentially the name? I am not sure what your data will be.
Upvotes: 3