This question already has answers here:
How do I remove an object from an array with JavaScript? [duplicate]
(15 answers)
Closed 9 years ago.
How can I remove an object from an Array by id for example:
users = [{id: "10051", name: "Mike Coder"},{id: "4567", name: "Jhon Second"}]
Say I want to remove user with id "10051" using javascript, I tried searching the internet but couldn't find anything?
plus I do not want to use underscore!
plus I do not want to use underscore!
The native method for this is .filter():
var removeId = "4567";
users = users.filter(function (user) { return user.id !== removeId; });
Note that it requires the engine be ES5-compatible (or a polyfill).
You could use .filter method of array.
users = users.filter(function(el) {return el.id !== '10051'});
for (var i = 0; i < users.length; ++i)
{
if ( users[i].id == "10051" )
{
users[i].splice(i--, 1);
}
}
var users= [{id:"10051", name:"Mike Coder"},{id:"4567", name:"Jhon Second"}];
/* users.length= 2 */
function removebyProperty(prop, val, multiple){
for(var i= 0, L= this.length;i<L;i++){
if(i in this && this[i][prop]=== val){
this.splice(i, 1);
if(!multiple) i= L;
}
}
return this.length;
}
removebyProperty.call(users,'id',"10051");
returned value: (Number) 1
Related
This question already has answers here:
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 5 years ago.
I need to join two strings in the name of the object in for loop in mongoose and expressjs like in example:
for(var i = 0; i < 2; i++)
{
EnrollSessions.update({ CookieId: req.cookies.UserEnrollSession },
{$set: {"Files.File"+i+".RealName": file.originalname},
function (err,data) {
console.log(data);
});
}
As a result i need update value of Files.File1.Realname, Files.File2.Realname.
Is it possible?
Thank you for help in advance.
In your example the for loop runs with i values 0 and 1 which would rename File0 and File1.
You can use "Files.File"+ (i + 1) +".RealName".
A better approach would be to create the update object in the for loop and the send it to mongo afterwards.
let obj = {
};
for(var i = 0; i < 2; i++)
{
let name = "Files.File" + (i + 1) + ".RealName";
obj[name] = file.originalname;
}
EnrollSessions.update({ CookieId: req.cookies.UserEnrollSession },
{$set: obj},
function (err,data) {
console.log(data);
});
Or, if there are only 2 files you can hard code them by hand in the same update object instead of the for loop.
This question already has answers here:
Looping through array and removing items, without breaking for loop
(17 answers)
Closed 5 years ago.
I'm working on a small exercise:
The problem is that I want this:
=> ['kept','kept']
But instead, I keep getting this:
function keep(array, keeper) {
//This will return an array of undefined's and 'kept's
// =>[ 'kept', undefined, 'kept', undefined, undefined ]
matchingNumbers = array.map(function matching(element){
if (element === keeper) {
return element;
}
});
//Eliminate all undefined's from the matchingNumbers array
matchingLength = matchingNumbers.length;
for (var i = 1; i < matchingLength; i++) {
if(matchingNumbers[i] === undefined) {
(matchingNumbers.splice(i, 1));
}
}
return matchingNumbers;
}
keep(['kept', 'thirty', 'kept', 2, 1], 'kept')
I'm trying to splice off all of the undefined's in matchingNumbers with the for-loop, so why is there a last undefined remaining?
When a function doesn't execute a return statement, it returns undefined by default. array.map() puts the return values of the function into the resulting array, and this includes those undefined values.
You should use array.filter instead of array.map:
matchingNumbers = array.filter(function matching(element){
return element === keeper;
});
My guess is because you're starting i at 1 instead of 0. Also, as #Wali mentioned, you're changing the array length while iterating over it. To solve that, go through the array in reverse order:
for (var i = array.length; i > 0; i--) {
...
}
As a side note, you can achieve what you want using Array.filter rather than dealing with mapping and splicing.
This question already has answers here:
Equivalent of Underscore _.pluck in pure JavaScript
(10 answers)
Closed 7 years ago.
I'm looking at extracting keys from an Object and push them to an array in Javascript (Nodejs). An example would be:
var obj = [{tag: 'ft001', addr: 'DB415.DBD2'}, {tag: 'ft001', addr: 'DB415.DBD6'}];
function extractKey(arr, keyName) {
// Result: ['ft001', 'ft002'];
}
How would I go about doing this?
Use Array.prototype.map():
var obj = [{tag: 'ft001', addr: 'DB415.DBD2'}, {tag: 'ft001', addr: 'DB415.DBD6'}];
function extractKey(arr, keyName) {
return arr.map(x=> x[keyName])
}
I think it's rather self-explaining.
if a typo [ 'ft001', 'ft002'], then the following would you be useful:
function extractKey() {
var result = [];
for (var index = 0; index < obj.length; index++) {
result.push(obj[index].tag);
}
return result;
// Result: ['ft001', 'ft001'];
}
This question already has answers here:
How do I remove an element in a list, using forEach?
(5 answers)
Closed 7 years ago.
Is it possible to remove something from an array using foreach?
var array = [1,2,3,4,5,6,7,8];
array.forEach(function(data){
if (data == 4) {
// do something here
}
});
console.log(array);
I would advise against using the forEach function. It affects the iterator and skips the next item. Better: use a reverse for loop and remove the item by index.
var array = [1,2,3,4,5,6,7,8];
for (var i = array.length - 1; i > -1; i--) {
if (array[i] == 4) {
array.splice(i, 1);
}
}
Fiddle: https://jsfiddle.net/uu94y8Lx/
I would not recommend this. The forEach function iterates over the array and when you remove the current or a previous item it will skip the next item in the array. That being said if you really want to remove an item despite the problems you will run into it is possible to remove an item with array.splice(data, 1).
Try like this:
array.forEach(function(data){
if (data == 4){
console.log('done')
array.splice(data, 1);
}
});
Also as commented by mario its not recommended to modify the array you're looping on, so you can do like this:
var array1 = [];
array.forEach(function(data){
if(array.length === 4){
array1.push(data);
}
});
Also you can use the for loop like this:
var array = [1,2,3,4,5,6,7,8],i;
for (i = 0; i < array.length; ++i) {
if (array[i] === 4) {
array.splice(i--, 1);
}
}
console.log(array);
This question already has an answer here:
How to filter a javascript object array with variable parameters
(1 answer)
Closed 9 years ago.
I am looking for a way to filter my JavaScript Array() columns where the parentId is equal to a variable passed into the method.
// Array decleration
var columns = []; // Columns
//...
for (var i1 in columns) {
if (columns[i1].parentId == listItem) {
//...
Could anybody recommend the easiest way to filter this using either plain JavaScript or jQuery to avoid using the if statement as shown above?
var filteredColumns = columns.filter(function(column) {
return column.parentId == listItem;
});
array = [1,2,3,4,5];
result = $.grep(array, function(n,i) {
return n > 3;
});
This will return an array of filtered elements where the results are greater than 3. Here n is the element in consideration, and i the index of the element. So as per your requirement, the code can run like this:
resultArray = $.grep(columns,function(n,i) {
return n == parentId;
});
Use ES5 Array's filter method:
var filtered = columns.filter(function (item) {
return item.parentId === listItem
});
In the link above there is also a shim for old browsers.
You can also doing that manually:
var filtered = [];
for (var i = 0, item; item = columns[i++];)
if (item.parentId === listItem) filtered.push(item);
Don't use for…in to iterate over Array.