Chantun
Chantun

Reputation: 91

for loop efficiency, make two for loops into one

So I have 2 separate 2D array, they are not necessarily the same length, and I want to make an object for each. I made this:

var obj1 = {},
    obj2 = {};

    for (var i=0; i<arr1.length; i++) {

      obj1[arr1[i][1]] = arr1[i][0];

    }  

    for (var j=0; j<arr2.length; j++) {

      obj2[arr2[j][1]] = arr2[j][0];

    }

My question is if there is a way to make this with only one loop. Thanks!

Upvotes: 0

Views: 192

Answers (5)

x-ray
x-ray

Reputation: 3329

Inspired by Pete's and eur00t's answers, I suggest this one:

var commonLength = Math.min(arr1.length, arr2.length);

for (var i = 0; i < commonLength; i++) {
    obj1[arr1[i][1]] = arr1[i][0];
    obj2[arr2[i][1]] = arr2[i][0];
}

for (var i = commonLength; i < arr1.length; i++) {
    obj1[arr1[i][1]] = arr1[i][0];
}

for (var i = commonLength; i < arr2.length; i++) {
    obj2[arr2[i][1]] = arr2[i][0];
}

As the question is about efficiency, I made a jsperf test case to compare the solutions.

Upvotes: 0

Pete
Pete

Reputation: 58422

You could try something like this:

var obj1 = {},
    obj2 = {},
    length = Math.max(arr1.length, arr2.length);  // get max array length

for (var i = 0; i < length; i++) {                // loop max array length

  if (i < arr1.length) {                          // do check for arr1
    obj1[arr1[i][1]] = arr1[i][0];   
  }

  if (i < arr2.length) {                          // do check for arr2
    obj2[arr2[i][1]] = arr2[i][0];
  }
}

As pointed out, this may be less efficient than 2 separate loops,

Although it also may be more efficient

Upvotes: 3

pooja
pooja

Reputation: 1

var obj1 = {},   

for (var i=0; i<arr1.length; i++) {

  obj1[arr1[i][1]] = arr1[i][0];

}  

for (var j=0; j<arr2.length; j++, i++) {

  obj2[arr2[i][1]] = arr2[j][0];

}

Hope this will you

Upvotes: -2

Bergi
Bergi

Reputation: 664395

What you really want here is a function abstraction that removes the duplication. There is nothing to make this more efficient (if you meant time complexity, not developer efficiency):

function arrToObj(arr) {
    var obj = {};
    for (var i=0; i<arr.length; i++) {
        obj[arr[i][1]] = arr[i][0];
    }  
    return obj;
}
var obj1 = arrToObj(arr1),
    obj2 = arrToObj(arr2);

The loop is still executed twice, but it's only written once.

Upvotes: 2

eur00t
eur00t

Reputation: 1548

Something like this should work:

var obj1 = {},
    obj2 = {};

for (let i = 0; i < arr1.length && i < arr2.length; i++) {

    obj1[arr1[i][1]] = arr1[i][0];
    obj2[arr2[i][1]] = arr2[i][0];
}

if (arr1.length > arr2.length) {
    for (let i = arr2.length; i < arr1.length; i++) {
        obj1[arr1[i][1]] = arr1[i][0];
    }
}

if (arr2.length > arr1.length) {
    for (let i = arr1.length; i < arr2.length; i++) {
        obj2[arr2[i][1]] = arr2[i][0];
    }
}

Upvotes: 0

Related Questions