Array iteration with iself - javascript

I have an array of values like:
["34.44","55.22","15.32","21.67","98.76","14.57"]
and I want to iterate between themselves like
Calculate(34.44, 55.22);
Calculate(34.44, 15.32);
Calculate(34.44, 21.67);
Calculate(34.44, 98.76);
Calculate(34.44, 14.57);
Calculate(55.22, 15.32);
Calculate(55.22, 21.67);
Calculate(55.22, 98.76);
and so on...
what would be best way to iterate them in Javascript?
I was easily thinking having two arrays with same values and interate between first array and second array but could exists a better way for performance...
Thanks in advance to everyone!
Cheers,
Luigi

for( var i=0; i<myarray.length; i++ ) {
for( var j=i+1; j<myarray.length; j++ ) {
Calculate( myarray[i], myarray[j] );
}
}

Array.forEach doesn't allow to do this kind of iteration, your best option is to just make two loops on the index:
for (var i=0; i<x.length; i++) {
for (var j=i+1; j<x.length; j++) {
... do whatever you need with x[i], x[j] ...
}
}
if instead you need to process x[a], x[a] pairs (i.e. the same element twice) and also both x[a], x[b] pair and x[b], x[a] pair then forEach can shorten the code (and probably will run faster).
x.forEach(function(x1){ x.forEach(function(x2){
... do whatever you weant with x1, x2 ...
})});
but note that forEach will iterate only over the elements that have been actually assigned, not in all the range 0..length-1. For example after
x = [];
x[2] = 42;
the loop x.forEach(...) will not iterate over the undefined elements x[0] and x[1].

You can use nested forEach methods on the array.
var array = ["34.44", "55.22", "15.32", "21.67", "98.76", "14.57"];
array.forEach(function(numberLeft, indexLeft) {
array.forEach(function(numberRight, indexRight) {
// skip previous numbers and itself
if (indexLeft >= indexRight)
return;
Calculate( numberLeft, numberRight );
});
});

Related

For-in loops with two variable javascript

Is this possible?
Two variable in for-in loops simulatenous?
for (var i in shear_x && var j in moment_x) {
var overturning_moment = (shear_x[i].results + moment_x[j].results)*moment_arm;
}
Your code implies, at least to me, that you really want a single loop counter applied over both objects, at the same time. I would suggest using a single for loop over the common length of the two objects:
var length = // length of shear_x
for (var i=0; i < length; ++i) {
var overturning_moment = (shear_x[i].results + moment_x[i].results) * moment_arm;
// rest of your loop code
}
If I interpreted your requirement incorrectly, then the only option which might come to mind is two nested loops, something like this:
for (var i in shear_x) {
for (var j in moment_x) {
// your code
}
}

for loop to print out multiple arrays with similar names

I've got multiple arrays, like so:
bugNames0 = ["wasp", "roach", "stinkbug", "mantis"];
bugNames1 = ["hornet", "beetle", "ant", "termite"];
bugNames2 = ["gnat", "fly", "grub", "chigger"];
bugNames3 = ["flea", "bed-bug","maggots", "cricket"];
Next up I have this for loop:
function bugLoop() {
for (var i=0; i < 4 ; i++){
console.log(bugNames0[i]);
}
}
That will successfully print the first array to console, or each individually if I manually update the number in the array's name.
But is there a way to do something more like this? This following code bit doesn't work, but I hope it explains what I am trying to do:
for (var i=0, j=0; i < 4; i++) {
console.log(bugNames(i)[j]);
}
}
Here i represents the bugName#, which I would like to get to update through 0 - 3 as the loop runs, printing out only the first option of each array represented by j.
Goal outcome printed to console would be:
"wasp", "hornet", "gnat", "flea"
Or something like that.
If possible I would like solutions only using vanilla JS as I'm working on a project (self assigned exercise) where I'm trying to complete it using vanilla. Kind of a force myself to get the know the language better exercise.
(Also, I've only been coding for 4 months, so sorry if this is a noob question. I couldn't find the answer online anywhere, just lots of loops on printing out arrays normally.)
If you can store your arrays within an array, that would be a better option.
For instance:
bugNames[0] = ["wasp", "roach", "stinkbug", "mantis"];
bugNames[1] = ["hornet", "beetle", "ant", "termite"];
bugNames[2] = ["gnat", "fly", "grub", "chigger"];
bugNames[3] = ["flea", "bed-bug","maggots", "cricket"];
Then you can loop through the bugNames array normally.
You could store all four arrays into one larger array (each bugNames array would simply be an element within this larger array). Let's call it bugCollection:
bugCollection = [["wasp", "roach", "stinkbug", "mantis"], ["hornet", "beetle", "ant", "termite"], ["gnat", "fly", "grub", "chigger"], ["flea", "bed-bug","maggots", "cricket"]]
Alternately, you could keep your variable storage of these arrays and say:
bugCollection = [bugNames0, bugNames1, bugNames2, bugNames3]
Then you could iterate through the larger array, logging out the index at each.
var oneFromEachArray = function(index) {
for (var i = 0; i < bugCollection.length; i++) {
console.log(bugCollection[i][index]);
}
}
oneFromEachArray(0) // Console logs 'wasp', 'hornet', 'gnat', 'flea'
You could try eval
for (var j=0; j < 4 ; j++){
for (var i=0; i < 4 ; i++){
eval("console.log(bugNames" + j + "[i]);");
}
}
You could use the function eval() like this:
for (var i=0, j=0; i < 4; i++) {
console.log(eval('bugNames' + i)[j]);
}
But did you already consider utilizing an array of arrays? Maybe that would be a cleaner way to achieve the same thing.
You can always access your variables using window object. Please use following code to access your variable dynamically.
for (var i=0, j=0; i < 4; i++) {
console.log(window["bugNames"+i][j]);
}

How to remove some items by iterating over the array of objects?

I want to iterate through the array of object and remove some of them based on some condition.
I used splice for removing the items to preserve an orderly count of items.
Then each time the item removed I would decrease the count.
But for some reason it never works:
var arr=[{img:1},{img:2},{img:3},{img:4}];
for (var i=0, count= arr.length; i < count; ) {
if ( this.arr[i].img==3 ) {
this.arr.splice(i,1);
count--;
}else i++
};
alert(JSON.stringify(arr));
​
...any ideas?
Looping backwards should do the trick. This avoids using counters and resetting the counter when removing an entry due to the "retreating" values.
var i;
for (i = arr.length; i--;) {
if (arr[i].img === 3) {
arr.splice(i, 1);
}
};
Simpler to loop through the array backwards, then you don't have to adjust the iterator:
var i = arr.length;
while ( i-- ) {
if ( arr[i].img == 3 ) {
arr.splice(i,1);
}
}
I have dealt with this same difficulty before. My solution was to loop through the array and compose another array of elements to remove. loop through the list of elements to remove in reverse and remove them. This worked well for me.
Michael G.
You're referring to this.arr instead of just arr.
Delete the two this. from the code, and it works. :-)
try this loop, I haven't tested but should work.
var arr=[{img:1},{img:2},{img:3},{img:4}];
for (var i=arr.length-1; i >= 0; i--) {
if ( arr[i].img==3 ) {
arr.splice(i,1);
}
};
alert(JSON.stringify(arr));

Javascript loop an array

I have a javascript array written like this...
var json = [
{"id":"1", "title":"Test 1", "comment":"This is the first test"},
{"id":"2", "title":"Test 2", "comment":"This is the second test"}
];
what I am trying to do is get each one of the ids.
I have been trying this
for(x in json[0]){
alert(x.id);
}
But no luck, can someone point me in the right direction? Please and thank you :)
x in your example is giving you the indexes of you array, not the objects. You could do:
for(x in json) {
alert(json[x].id);
}
but to loop through an array you're really better off with a "regular" for loop
for (var i = 0, max = json.length; i < max; i++) {
alert(json[i].id);
}
Any modern browser will allow you to do it easily:
var ids = json.map(function(i) { return i.id; });
// and now you have an array of ids!
Sadly, "modern" does not include IE 8 and earlier.
You can also do the "mundane" form, which is guaranteed to work in all browsers. I see Adam Rackis has beat me to it though, so I 'll go upvote his answer and you should probably do so as well.
This is one possible solution:
var json = [{"id":"1","title":"Test 1","comment":"This is the first test"},{"id":"2","title":"Test 2","comment":"This is the second test"}];
for (var i = 0, len = json.length; i < len; i++) {
alert(json[i].id);
}
A for(x in y) loop in JavaScript gives you the indexes in that array (e.g., so that x[y] gives you the current element).
The two proper ways to loop through an array in JavaScript are:
for(x = 0; x < y.length; x++) { // (this can only loop through arrays)
// do something with y[x]
}
for(x in y) { // (this can loop through objects too)
// do something with y[x]
}

javascript array for loop i+1 returning undefined

array ref.length = 7 (0 - 6), and I want to try to match ref[0]['x'] to ref[1]['x'] I am doing this:
for(var i=0;i<ref.length;i++){
if( ref[i]['x'] != ref[i+1]['x'] && ref[i+1]['x'].length > 0 )
//do something
}
The for loop is iterating all the way to array number 6 then element 6+1 is blank so I get an error on the if statement line saying ref[i+1] is undefined....
is there a better way to do this?
Better:
for (var i=ref.length-2;i>=0;i--)
Javascript will evaluate the condition on each iteration, so it's generally preferable go backwards instead. With this construct "ref.length" is only evaluated once. Another alternative I like which will perform the same:
var i=ref.length-1;
while (i--) {
}
(Normally you'd be i=ref.length-1 in the first example, and i=ref.length in the second, but you're trying to stay one less than the array length).
for (var i=0; i<ref.length-1; i++) { // Note the "-1".
This way when you use the index i+1 you're still in bounds.
for (var i = 0; i < ref.length - 1; i++)
What about:
for(var i=0;i<ref.length-1;i++){
If you just use ref.length-1 won't that solve your problem? I might not fully understand what you're asking.
Here's a simple solution.
Just count the counter again.
if( ref[i]['x'] != ref[++i]['x'] && ref[++i]['x'].length > 0 )

Categories

Resources