How to remove single object in array from multiple matching object
Swift 2
Solution when using a simple Swift array:
var myArray = [1, 2, 2, 3, 4, 3]
if let index = myArray.indexOf(2) {
myArray.removeAtIndex(index)
}
It works because .indexOf
only returns the first occurence of the found object, as an Optional (it will be nil
if object not found).
It works a bit differently if you're using NSMutableArray:
let nsarr = NSMutableArray(array: [1, 2, 2, 3, 4, 3])
let index = nsarr.indexOfObject(2)
if index < Int.max {
nsarr.removeObjectAtIndex(index)
}
Here .indexOfObject
will return Int.max
when failing to find an object at this index, so we check for this specific error before removing the object.
Swift 3
The syntax has changed but the idea is the same.
Array:
var myArray = [1, 2, 2, 3, 4, 3]
if let index = myArray.index(of: 2) {
myArray.remove(at: index)
}
myArray // [1, 2, 3, 4, 3]
NSMutableArray:
let myArray = NSMutableArray(array: [1, 2, 2, 3, 4, 3])
let index = myArray.index(of: 2)
if index < Int.max {
myArray.removeObject(at: index)
}
myArray // [1, 2, 3, 4, 3]
In Swift 3 we call index(of:)
on both Array and NSMutableArray, but they still behave differently for different collection types, like indexOf
and indexOfObject
did in Swift 2.
Remove one object from an array with multiple matching objects
I think you have an XY-problem. Instead of an array, you should use a hash with number of occurrences as the value.
hash = Hash.new(0)
When you want to add an entity, you should do:
hash["a"] += 1
If you want to limit the number to a certain value, say k, then do:
hash["a"] += 1 unless hash["a"] == k
remove objects from array by object property
I assume you used splice
something like this?
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
}
}
All you need to do to fix the bug is decrement i
for the next time around, then (and looping backwards is also an option):
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
i--;
}
}
To avoid linear-time deletions, you can write array elements you want to keep over the array:
var end = 0;
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) === -1) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
and to avoid linear-time lookups in a modern runtime, you can use a hash set:
const setToDelete = new Set(listToDelete);
let end = 0;
for (let i = 0; i < arrayOfObjects.length; i++) {
const obj = arrayOfObjects[i];
if (setToDelete.has(obj.id)) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
which can be wrapped up in a nice function:
const filterInPlace = (array, predicate) => { let end = 0;
for (let i = 0; i < array.length; i++) { const obj = array[i];
if (predicate(obj)) { array[end++] = obj; } }
array.length = end;};
const toDelete = new Set(['abc', 'efg']);
const arrayOfObjects = [{id: 'abc', name: 'oh'}, {id: 'efg', name: 'em'}, {id: 'hij', name: 'ge'}];
filterInPlace(arrayOfObjects, obj => !toDelete.has(obj.id));console.log(arrayOfObjects);
How to remove object from array except matching value?
You may use Array.filter
along with Array.includes
:
var items = [{"id":"88","name":"Lets go testing"},{"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}];var arr = ["88", "108"];
const result = items.filter(item => arr.includes(item.id));console.log(result);
How to remove object if object matches
One way is to use Array#filter
with Array#some
+ JSON.stringify()
for comparison.
Note that Array#filter
returns a new array. So the variable needs to be reassigned.
let originalArray = [
{name: 'abc', country: 'eng'},
{name: 'xyz', country: 'ind'},
{name: 'pqr', country: 'us'}
];
let objectToBeRemove = [
{name: 'pqr', country: 'us'}
];
originalArray = originalArray.filter(obj =>
objectToBeRemove.some(objToRemove =>
JSON.stringify(objToRemove) !== JSON.stringify(obj)
)
);
console.log(originalArray);
How do I remove an object from an array with a matching property?
You could use Array#filter
method:
food = {
id: 1,
name: 'Pizza',
price: 16
};
orders = [
{ food_id: 2, table_id: 5 },
{ food_id: 2, table_id: 5 },
{ food_id: 1, table_id: 5 },
{ food_id: 3, table_id: 5 },
{ food_id: 1, table_id: 5 }
];
removeFoodOrder(food: Food): void {
this.orders = this.orders.filter(({ food_id }) => food_id !== food.id);
}
Edit:
Since your array allows duplicate elements and you want to remove only the first match, you could use the Array#findIndex
+ Array#filter
methods:
const foundIndex = this.orders.findIndex(({ food_id }) => food_id === food.id);
this.orders = this.orders.filter((_, index) => index !== foundIndex);
Remove matched object from deeply nested array of objects
If you don't mind modifying the parameter tree in-place, this should do the job. Note that it'll return null
if you attempt to remove the root.
const tree = { id: 1, name: "Dog", parent_id: null, children: [ { id: 2, name: "Food", parent_id: 1, children: [] }, { id: 3, name: "Water", parent_id: 1, children: [ { id: 4, name: "Bowl", parent_id: 3, children: [] }, { id: 5, name: "Oxygen", parent_id: 3, children: [] }, { id: 6, name: "Hydrogen", parent_id: 3, children: [] } ] } ] };
const removeFromTree = (root, nameToDelete, parent, idx) => { if (root.name === nameToDelete) { if (parent) { parent.children.splice(idx, 1); } else return null; } for (const [i, e] of root.children.entries()) { removeFromTree(e, nameToDelete, root, i); } return tree;};
console.log(removeFromTree(tree, "Oxygen"));
Lodash Remove objects from array by matching ids array
As you mentioned you need the _.remove
method and the specific condition you mention is whether the removeItem
array contains the id
of the checked element of the array.
var removeElements = _.remove(a, obj => removeItem.includes(obj.id));
// you only need to assign the result if you want to do something with the removed elements.
// the a variable now holds the remaining array
Related Topics
Swift Language Multicast Delegate
Routing Between Points with Mapbox
Unrecognized Selector Sent to Instance Swift 3
How to Change the Number of Decimal Places iOS
Swift/How to Call Delegate with Popviewcontroller
Swift - How to Open Another Viewcontroller with Collectionviewcell Inside Uitableviewcell
Backgroundtimeremaining Returns (35791394 Mins)
@Fetchrequest + Case-Insensitive Sorting - Swiftui & Coredata
How to Deal with Dynamic Sections and Rows in iOS Uitableview
Swift Swipe Navigation Table Views
Nsexceptionallowsinsecurehttploads Not Working for Ip Addresses
iOS Development App Startup Crash
Target Is Not Found, Please Reconnect the Device, Xcode:Device Support File
How to Create an Alert in a Swift File Model That Works for Various View Controller
Xcode Constraint Break When Switching Between Text Fields Without Dismissing Keyboard
Non-Main Bundle File as Alert Sound
Countdown with Several Decimal Slots, Using Nstimer in Swift