Javascript - why isn't my array loop working? [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have a list of objects (data), I am doing this:
for (var i = 0; data.length < i; i++) {...}
But it doesn't work. When I use this:
for (var i in data) {
It works, but is looping three times, when there is only one object, in this case i is: 0 (correct), indexOfObject (wtf), removeItem (wtf).
Why my first expression is not working? What are those two werid i values? Am I doing something wrong?
Edit: Since this thing is a bit complicated, the best I can do is provide a screenshot of my data object: screenshot

Check your for loop statement, the condition of the loop (data.length < i) is the other way round and probably never fulfilled.
It should be:
for (var i = 0; i < data.length; i++)
{
// Now write your code
}

If you really have an array —
var a = ["hello", "world"];
or
var a = new Array();
a[0] = "hello";
a[1] = "world";
Then your first loop (with the index variable) is correct. You should use the in style for loop for iterating over properties of objects, but the indexed style for the numerically indexed properties of an array.
edit — oops good call #Sachin - your for loop test is backwards.
If you have a plain object and you want to iterate through its properties, but skip properties found on the object's prototype chain, you can do something like this:
for (var name in obj) {
if (obj.hasOwnProperty(name)) {
var value = obj[name];
// do stuff
}
}

I could see from the above given code, you have given wrong condition inside the for loop. First, you are initializing the variable i to 0, and then checking data.length<0. Can any length value be less than zero??
you can use it like:-
for (var i = 0; i<data.length; i++) {...}
Try it will work.

Related

how to loop through array (array of objects) starting at a specific index to the last and alter properties in the object in Javascript? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
let library = []; //this stores each object
Each object has a property called' id' where a number is stored, this represents the index of the object in the library array. Basically when an object is deleted from the library I want to get all the objects in the array that come after the deleted object and minus 1 from the id property.
function updateId(index) {
for (let i = index; i <= library.length; i++) {
library[i].id - 1;
}
}
So far I have this function where the argument index is the position in the array where the object was deleted. I am getting a reference error with that last line of code
Instead of i <= library.length try i < library.length.
Currently that line is saying "continue this for loop so long as i is less than or equal to the length" ... but remember, i (ie. indices) are zero-based, while lengths aren't. This means that you'll actually loop past where you want.
Note this is just one of many ways to solve this!
You're almost there. There are a few things that your code needs:
to have access to the 'library' inside of your function, you should pass it into the function. Functions should only operate on variables that they received as arguments.
your for loop, should go on if i is SMALLER THAN not SMALLER EQUAL to the length
if you're changing the 'library' in a function, you need to return it, and overwrite the original.
function updateId(library, startingAtIndex) {
for (let i = startingAtIndex; i < library.length; i++) {
library[i].id -= 1;
}
return library
}
things = [{name:'a', id:1},{name:'c', id:3},{name:'d', id:4}]
things = updateId(things, 1)
console.log(things)

Does it run faster having assigned the vairable before the loop with Javascript and block scope? [duplicate]

This question already has answers here:
Is reading the `length` property of an array really that expensive an operation in JavaScript?
(6 answers)
Closed 1 year ago.
Is this true:
Statements or assignments that can be placed outside the loop will
make the loop run faster.
Bad:
var i;
for (i = 0; i < arr.length; i++) {
Better Code:
var i;
var l = arr.length;
for (i = 0; i < l; i++) {
https://www.w3schools.com/js/js_performance.asp
Update:
What is the purpose of declaring i before the loop?
It could make the code a tiny bit faster. In the first snippet, every time there's an iteration, the engine has to evaluate
arr.length
looking up the size of the array which might take a bit more processing time than looking up what integer a plain variable refers to.
In the second snippet, you only have to look up the size of the array once, instead of on every iteration.
That said, given how fast computers are nowadays, this consideration is almost certainly irrelevant in 99.9% of situations. Better to write clean and readable code first, and then optimize performance only if it becomes a problem.

Javascript: Associative arrays by altering Array.prototype - deprecated? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
It seems to me that one of the big downsides of javascript is that there are no associative arrays. Objects don't provide order, arrays don't provide keys.
There is also the possibility of arrays containing objects:
[{key1:value1}, {key2:value2}]
But as far as I know, there is no easy way to access elements by keys in this approach (without having to iterate through all elements).
That's why I started to think about the following approach, that is making an array associative by adding a element mapper:
Array.prototype.addKeyToLastElement = function(key) {
if (!this.elementMapper) this.elementMapper = {};
this.elementMapper[key] = this.length-1;
}
Array.prototype.getElementByKey = function(key) {
if (this.elementMapper && this.elementMapper[key] !== undefined) {
return this[this.elementMapper[key]];
}
else {
return undefined;
}
}
var test = [];
test.push(1);
test.addKeyToLastElement('a');
test.push(3);
test.addKeyToLastElement('b');
// get element by key
console.log(test.getElementByKey("a"));
I know that this is far from perfect, it's just a first try to see if it works. I was just wondering why I couldn't find any similar solutions.
Is this approach deprecated? If yes, what are the best alternatives?
My minimal requirements are:
Access elements by keys (retrieve/ alter value)
Maintain the elements order
Sort elements both by key and value
arrays don't provide keys
But as far as I know, there is no easy way to access elements by keys
in this approach (without having to iterate through all elements)
If interpret Question correctly, you could assign an alphabetic or other "key" as an index identifier and use a numeric identifier to access the same element within the array
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var arr = [];
for (var i = 0; i < alphabet.length; i++) {
arr[alphabet[i]] = arr[i] = alphabet[i]
};
console.log(arr["a"], arr[0], arr["z"], arr[25])
Is this approach deprecated? If yes, what are the best alternatives?
It is not deprecated, but it is not a good idea and hence a bad coding practice for following main reasons
These extra properties are not included in JSON serialisation.
These properties would be thrown away if you do an array operation like arr = arr.slice(1) which leads to un-expected behaviour.
But you can still sort the object like this (in your question)
[{key1:value1}, {key2:value2}]
by doing
var arr = [{key1:value1}, {key2:value2}];
arr.sort(function(a,b){
return a[Object.keys(a)[0]] - b[Object.keys(b)[0]];
})

How to change the given below json array? [duplicate]

This question already has answers here:
Extract each value of a single property from an array of objects in jQuery
(5 answers)
Closed 9 years ago.
I have a JSON array in the following format:
[{"country":"Algeria"},{"country":"Africa"},{"country":"America"},{"country":"Libiya"}]
I need to change it as follows:
{"Algeria","Africa","America","Libiya"}
How do I do that using Jquery or JavaScript?
In javascript:
var myArray = [{"country":"Algeria"},{"country":"Africa"},{"country":"America"},{"country":"Libiya"}];
var myNewArray = [];
for (var item in myArray) {
var country = myArray[item].country;
myNewArray.push(country);
}
alert(JSON.stringify(myNewArray));
You're actually have the wrong notation in your question. The end result you want should have square brackets ([]), not curly braces({}). Curly braces indicate an object instead of an array but you are not using a key-value structure so the end-result you have above is actually invalid.
Instead it seems you want ["Algeria","Africa",America","Libiya"] as the end-result.
Assuming you mean literally changing the array you have rather than creating a new one and assuming you are using JavaScript:
var arr = [{"country":"Algeria"},{"country":"Africa"},{"country":"America"},{"country":"Libiya"}], // declare your array upfront (but this could be a `JSON.parse()` call)
i = 0, // counter
l = arr.length; // limit/length of array
for (i; i < l; i += 1) {
arr[i] = arr[i].country; // Replace object with value of country property.
}
// `arr` will now be `["Algeria","Africa",America","Libiya"]`
Of course you might want to introduce some checks to ensure that every element of the array has a property called country and some way to deal with that in the rewritten array. But I'll leave you with this for now, see how you get on. This should work if your array is valid to begin with.

How do I add the output from a function to an array in JavaScript [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've been encountering this problem a few times. How to add the output from a function, rather than the function itself to an array in JavaScript. Consider the following:
function getRandomValue(){
returns a random number
}
myArray = [getRandomValue(), getRandomValue()];
Is it possible to add just the random numbers and not the function itself to the array?
What you have already does populate the array with the return values of the function:
function getRandomValue(){
//returns a random number
}
var myArray = [getRandomValue(), getRandomValue()]; // Call the function
var myArray2 = [getRandomValue, getRandomValue]; // Reference to the function
The parentheses following the identifier cause the function to be invoked, and the return value of it will be placed at the appropriate index of the array.
Were you to remove the invoking parentheses as shown above, you would be populating your array with references to the function, rather than the values returned by it.
You can use variables.
var a = getRandomValue();
var b = getRandomValue();
myArray = [a,b];
However, as said in comments, when you call the function in the array, you put the result in the array, not the function itself. So you have exactly the same behavior as with my solution.
Try This:
just put it into a loop if you want more then one values.
var myArray= [];
console.log(myArray.push(Math.random()));
Another way would be to use the array_push function:
myarray.push(getRandomValue());

Categories