This question already has answers here:
Remove array element based on object property
(12 answers)
Closed 4 years ago.
I have an array like this
var items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
I would like to delete an object from the array that matches id = 2
Here is my solution
//find the corresponding object
let obj=items.find((item) => item.id=='2');
//loop through the original and delete
Is there any other way to do this more efficiently??
I would like to suggest using splice, this doesn't change the reference of the existing array but just removes the desired element..
let items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
let indexToRemove = items.findIndex((eachElem) => {return eachElem.id == 2})
items.splice(indexToRemove, 1)
console.log(items)
Use Array#filter function for deleting item/s from the array. It actually returns a new array containing those items which corresponds to the predicate.
let items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
let filtered = items.filter(item => item.id !== '2');
console.log(filtered);
For removing from the original array
let items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
let index = items.findIndex(item => item.id === '2');
items.splice(index, 1);
console.log(items);
You can check the console :D
var items = [{id:'1',token:'jj'},{id:'2',token:'kk'}, {id:'4',token:'kk'}, {id:'2',token:'kl'}];
items.forEach(item =>{
if(item['id'] == '2') items.splice(items.indexOf(item),1)
})
console.log(items)
You can use splice() with forEach() too:
var items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
items.forEach((item, index) => {
if(item.id === '2'){
items.splice(index,1);
}
});
console.log(items);
Related
I am trying to filter through an array of objects and delete one of the object but keep the rest inside an array of objects but i keep returning either an array of arrays or i create nested objects. Is it possible to send in an array of objects and return and array of objects without that specific object? Below is the code I have been trying to work with.
function deleteWorkout(workoutName) {
const updatedArray = myWorkoutToDisplay.map((item) => item.newWorkToAdd.filter((workout) => workout.name !== workoutName))
const objectArray = [{updatedArray}]
const newWorkToAdd = objectArray.filter(e => e.length)
const workouts = [{newWorkToAdd}]
setMyWorkoutToDisplay(updatedArray)
}
You can easily do this with Array.prototype.filter. I guess the easiest way to delete 1 object is like this:
//let arr = arrayLike
//let objToDelete = whatever you want to delete
let newArr = arr.filter(obj => obj !== objToDelete)
newArr now has the array, without the deleted item. arr however still has it. To delete item by index, use this:
//let arr = arrayLike
//let ind = index to delete
let newArr = arr.filter((_, index) => index !== ind)
This question already has answers here:
The best way to remove duplicate strings in an array
(7 answers)
Remove Only One Duplicate from An Array
(6 answers)
Closed 1 year ago.
I have 2 apples in array. Filter method deletes all apples. Is there a way to delete only 1 of them.
var box = ['banana', 'apple', 'apple']
Output that I'm expectig:
box.filter((a) => a !== 'apple') => ['banana', 'apple']
Nothing built-in, no. You can remember whether you've seen it and always return true afterward:
const box = ["banana", "apple", "apple"];
let seenApple = false;
const filtered = box.filter((a) => {
if (seenApple) {
return true;
}
seenApple = a === "apple";
return !seenApple;
});
console.log(filtered);
Alternatively you could find the index of the first apple:
const appleIndex = box.findIndex(a => a === "apple");
...and then either filter by that index:
const filtered = box.filter((entry, index) => index !== appleIndex);
...or use splice to modify the array in-place.
Are you looking to remove duplicates?
If you just want an array with unique elements, you can do something like this
var unique_arr = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
You could take a closure with another variable for overriding the condition.
const
box = ['banana', 'apple', 'apple'],
result = box.filter(
(found => a => a !== 'apple' || found || !(found = true))
(false)
);
console.log(result);
This question already has answers here:
Remove array element based on object property
(12 answers)
Closed 3 years ago.
I want to remove some element in my array using splice method with if condition in my iteration. I do the following:
var list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}]
list.forEach(function (item, index) {
if (item.type == 'service'){
list.splice(index, 1)
}
}
//result: list = list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"}]
//expected: list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"}]
I expect the both element with type "service" will be removed, but only the first element is removed.
You can use Array.prototype.filter()
Code:
const list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}];
const resultList = list.filter(item => item.type !== 'service');
console.log(resultList);
When using forEach(), If the array is modified during iteration, other elements might be skipped
Why don't use Array.prototype.filter():
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
var list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}]
list = list.filter( item => item.type != 'service');
console.log(list);
I have an array of objects which has a nested parameter in it and I want to return only those array elements that pass filter based on that nested parameter which is in turn also an array of objects.
[{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]},
{q:3,w:5,props:{p:2, messages:[{status:false},{status:false},{status:false}]},
{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}
]
My aim is to filter only those objects that contain at least one message with status true.
In this example I would expect to get an array of two objects
[{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]},
{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}
]
Thanks for help and advice!
some() will let you check if a condition is true at least once. You can use that to filter: filter
let arr = [{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]}},{q:3,w:5,props:{p:2, messages:[{status:false},{status:false},{status:false}]}},{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}}]
let filtered = arr.filter(item => item.props.messages.some(m => m.status === true))
console.log(filtered)
Use filter.
var result= items.filter(item =>{
return item.props.messages.some(obj => obj.status === true)
})
I created this Fiddle:
http://jsfiddle.net/81ue32ra/2/
var items = [{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]}},
{q:3,w:5,props:{p:2, messages:[{status:false},{status:false},{status:false}]}},
{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}}
];
var result = items.filter(item =>{
return item.props.messages.some(obj => obj.status === true)
});
console.log(result);
Just filter the main array and check if some of the messages status property is true.
let data = your array;
data.filter(obj => obj.props.messages.some(message => message.status).length > 0)
For example consider the following array with objects.
var collection = [{name:'user1',phone:'203'},
{name:'user2',phone:'5050'},
{name:'user1',phone:'203'}]
Now I want to compare the each object with each other and give the result as.
var newCollection = {name:'user1',phone:'203', rowMatch:'true'},
{name:'user2',phone:'5050', rowMatch:'false'},
{name:'user1',phone:'203',rowMatch:'true'}
So, I want the new collecition like this where it compares and updates with new property when object properties match like the first and third object.
var newCollection = collection.map(item => {
item.rowMatch = !!collection.find(i => i !== item && i.phone === item.phone && i.name === item.name);
return item;
});
Here you're just using map to iterate through and check if each item has a duplicate that isn't the original.
You can use newCollection or manipulate in the collection like this
collection.forEach((item)=>{
item.rowMatch = (collection.filter((e)=>{return (e.name==item.name&&e.phone==item.phone)}).length>1)?'true':'false';
})
console.log(collection)
Simple is that.Here is working JSFiddle for it https://jsfiddle.net/touqeer/pgdsw9Le/1/ .
Create a hash function for your object type.
A simple concatenation of the fields seems to work in this case. Iterate through your collection and for each element, hash it, and put it in a table.
Keep track of the counts. When the count is greater than 1 you know you have a duplicate (row match)
JavaScript Hashmap Equivalent
use Array.prototype.find
var newCollection = collection.map((row, index) => {
if(row["rowMatch"])
return row;
rowMatch = !!collection.find((r,i) => i !== index && r.name === row.name && r.phone === row.phone);
row["rowMatch"] = rowMatch;
return row;
})