Finding specific objects in array to remove [duplicate] - javascript

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.

Related

JS array.includes() // array within array // [['a']].includes(['a']) returns false [duplicate]

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'])))

What is the purpose of the [i] in the for loop [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
I have some line of code that I don't fully understand. I am looking through objects in an api and was wondering what is the purpose of the [i] in d2.follows[i].user.display_name if the code is:
$.getJSON(followerURL, function(d2){
for(var i=0; i<d2.follows.length; i++){
var displayName = d2.follows[i].user.display_name;
following.push(displayName);
I'm searching through object to find the number of followers a channel has. is Here is an image of the object I would greatly appreciate an explanation of this block of code.
As per you JSON Object, it fetches the follows element, which is an array.
Then it takes each element in the follows array and get the user object and its attribute display_name.
Obj -> follows -> user -> display_name
This lists down all the display names of the users.
d2.follows should b an array of objects
To get the displayName from each objects, we should iterate through the array. The [i] helps to iterate through the array elements.
The [i] in d2.follows[i].user.display_name uses the i value from the for loop to set displayName. More or less it goes through the array one by one and reads a value.
I'm unfamiliar with the Twitch API, but if the follows array consists of people who are following someone, then follows.length will give you the amount of followers.
getJSON function return you this object here d2 main object returned from function. for(var i=0; i<d2.follows.length; i++) loop for get each item in the follows list. var displayName = d2.follows[i].user.display_name; here d2.follows[i] is a each item and each item have a user property which is a object and have a display_name property here you set last one property to displayName variable then you call following.push(displayName); following suspect is a array which is a have a push method

How to completely delete element from Javascript array [duplicate]

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.

Javascript - refilling one array from another [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 8 years ago.
I'm creating a simple question and answer game to help with revision and having trouble repopulating an array the second time around.
When a button is clicked the following code is executed.
if(setSelection == 0){
tempQuestions = chosenQuestion;
tempAnswers = chosenAnswer;
}
This works perfectly the first time.
When a correct answer is selected the following code removes the question and answer from temporary array, leaving the original intact.
tempQuestions.splice(randomQuestion,1)
tempAnswers.splice(selectedAnswer, 1);
When the button is pressed for a second time, after the 'game' is complete, the temporary array fails to refill even though I'm executing the same code.
Any ideas why the code above does not work on the second run?
EDIT
jsfiddle
You are creating a new reference to the same array, so when you modify the temp vars you also modify the object referenced by the chosen vars. You need to copy the array. A nice way is to add your own copy() prototype method to the Array object.
a shallow copy should do:
Array.prototype.copy = function(){
return this.slice(0);
}
If you need a deep copy
Array.prototype.copy = function(){
return JSON.parse(JSON.stringify(this));
}
Use it like this:
if(setSelection == 0){
tempQuestions = chosenQuestion.copy();
tempAnswers = chosenAnswer.copy();
}
Using .slice works.
tempQuestions = chosenQuestion.slice();
The slice() operation clones the array and returns reference to the original.

Moving element inside an object in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Array rotate()
I have a tricky question for you. I have an object who contain different values and I want to change the index of on element so My first element has to become the last or the third or whatever I want. Is that possible in javascript ??
var object = [{0},{1},{2}]
to
var object = [{2},{0},{1}]
This is an example of what I would like to do.
Thanks in advance.
Your from and to example is a little hard to understand the intent, but based on the body of your question asking
My first element has to become the last or the third or whatever I want
Writing a method to swap 2 elements in an array is easy enough:
function swapElements(a, x, y){
var temp = a[x];
a[x] = a[y];
a[y] = temp;
}
Live example: http://jsfiddle.net/pwY9L/
I assume you mean:
var array = [0,1,2];
It doesn’t really matter if the array contains numbers, objects or whatever. If you want to modify this array, there are many ways to do this in javascript andyou can read up about all the Array prototypes here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
F.ex, move the last one and place it first:
array.unshift(array.pop());

Categories