This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 7 years ago.
I am using this code to iterate over an array and delete the element if it contains no itemsToPost.
rssFeeds.forEach(function(feed, index, array){
if(feed.itemsToPost.length == 0){
delete rssFeeds[index]
}
});
However, the array that I receive from this, assuming that all elements are deleted looks like:
[ , ]
And when I run this against Lodash's method to test if an array is empty.
console.log(_.isEmpty(array))) // returns 'false'
How can I completely delete these elements such that the array is truly empty?
Update:
I've found a solution using Array.prototype.filter as was suggested, such as:
function hasNewItems(array) {
return array.itemsToPost.length > 0;
}
var newArray = rssFeeds.filter(hasNewItems)
console.log(newArray); // returns []
It isn't necessarily deleting the array but it has the desired effect.
delete is not the correct way to remove element from array, you should use rssFeeds.splice(index, 1) instead.
Related
This question already has answers here:
Why can't I use Array#includes for a nested array?
(5 answers)
How to compare arrays in JavaScript?
(61 answers)
Closed 3 months ago.
TL;DR: the JavaScript code below returns false where I'm expecting a true, what's the best workaround?
console.log([['a']].includes(['a']))
I'm pushing arrays into arrays (to work with google sheets ranges in apps script, but the behaviour is the same in regular JavaScript).
I'd like to check if my parent array (let's call it [['a']]) contains specific child array (such as ['a']).
Unfortunately array.includes() doesn't seem to work as expected when the parameter is an array. (the code above returns false when it should be true as far as I know)
Am I missing anything? What do you think would be the best workaround?
The problem is array comparison.
console.log(['a'] == ['a']); //false
As the .includes() method loops through the array on which it is being called, it checks each element to see if it is equal to the value being tested for, until it finds a match, or checks every element of the array. As you can see above, when the value being tested is an array, it will not work.
A work around would be to write your own .includes() function in which you loop through all the child arrays in the parent array, and for each child array, loop through every element, testing whether it is equal to the corresponding element in the test array. You can use the .every() method for this.
let array = [['a']];
function includesArray(parentArray, testArray) {
for (let i = 0; i < parentArray.length; i++) {
if (parentArray[i].every(function(value, index) { return value === testArray[index]})) {
return true;
}
}
return false;
}
console.log(includesArray(array, ['a'])); //true
console.log(includesArray(array, ['b'])); //false
One quick alternative is to compare the JSON strigified arrays instead of comparing arrays directly.
console.log([['a']].map(x => JSON.stringify(x)).includes(JSON.stringify(['a'])))
This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
Closed 7 years ago.
I have an array of data which stores an object with functions and other such info. I push these objects to the function for my draw function to execute.
But i do not know of a way to find a specific object in an array to remove it and thus stop drawing it.
For example i have an array structure like this:
var data = {
'fnc':function(){
updatePosition(spriteID);
drawSprite(spriteID);
},
'something':'here'
};
var drawOrder= [];
drawOrder.push(data);
There are many functions in this array and they are pushed dynamically depending on what i wish to draw.
What would be the best way to find the index of one of these objects and remove it from the array in this case?
indexOf() returns the index in the array of the element you're searching for, or -1. So you can do:
var index = drawOrder.indexOf("aKey");
if (index != -1)
drawOrder.splice(index, 1);
Splice:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
indexOf:
http://www.w3schools.com/jsref/jsref_indexof_array.asp
I'm not 100% this will answer your question cause is not clear at least to me.
If you want to remove the whole element but you are worried about founding the right index before actually splice the array you should use Array.indexOF
See this code below:
var data = {
'fnc':function(){
updatePosition(spriteID);
drawSprite(spriteID);
},
'type':'aabb'
};
var drawOrder= [];
drawOrder.push(data);
console.log(drawOrder);
drawOrder.splice(drawOrder.indexOf(data), 1);
console.log(drawOrder);
As the documentation reports:
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
This question already has answers here:
How can I reverse an array in JavaScript without using libraries?
(36 answers)
Closed 7 years ago.
I have an array as:
var arr = [1,2,3,4]
//Push and element to array
arr.push(5)
//Now, arr = [1,2,3,4,5]
I need to display my array as
Elements in array arr is:
5,1,2,3,4
Arr.reverse() gives me
5,4,3,2,1.
But i need
5,1,2,3,4
Simply use Array.prototype.reverse():
console.log(arr.reverse());
References:
Array.prototype.reverse().
This is the code you need to use :
arr.reverse();
Here is the w3school : http://www.w3schools.com/jsref/jsref_reverse.asp
This question already has answers here:
Remove Object from Array using JavaScript
(32 answers)
Remove an item from array using UnderscoreJS
(12 answers)
Closed 9 years ago.
I currently have a function that successfully removes an item from an array but only for a simple collection. I am trying to extend this so it also works for removing object from an array but stumped. Can anyone help? Here is what I got so far:
remove: function (arr, value) {
if (_.isObject(value)) {
//HOW TO HANDLE THIS, MAYBE USE THIS FOR HELP? _.where(arr, value)
} else {
//THIS WORKS!
if ($.inArray(value, arr) >= 0)
arr.splice($.inArray(value, arr), 1);
}
}
For the first if-statement, I am having trouble finding the index of the object. Using underscore.js I can find the object itself, but don;t know how to find the index so I can remove it from there. Any ideas to solve this or a better way?
This question already has answers here:
Deleting array elements in JavaScript - delete vs splice
(29 answers)
Closed 9 years ago.
I have an array like:
var abc = ["a","b","c"];
And the indexes are 0,1,2
Suppose, I want to delete the 2nd item "b" and I the indexes swipe!
Out put:
abc = ["a","c"]
and the indexes are 0,1
How can I achieve this?
Use the splice function :
abc.splice(1,1) // from index 1, removes 1 element
Be careful that this changes the original array.
Use splice(). E.g:
abc.splice(1, 1);
would perform what you wanted in your example. abc[1] would now be "c".
You can use the array splice abc.splice(1,1);
Details:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice
Have a look on it... I think this is what you want...
var arr = ["a","b","c"];
arr.splice(1,1);
alert("["+arr.indexOf('a')+","+arr.indexOf('c')+"]");