简体   繁体   中英

Compare same index of two array having same length

I have two arrays with same length

array1 = [12,13,14,15,16]
array2 = [22,32,45,11,7]

Now I want to compare only the same index value in a for loop in javasacript ex:

array1[0] < array2[0]
array1[1] < array2[1]
array1[2] < array2[2]

and if value of array1[index] is less than array2[index] it return true

I suppose the output must be a boolean array. For this, you can use map method by passing a callback function.

 array1 = [12,13,14,15,16] array2 = [22,32,45,11,7] result = array1.map(function(item, i){ return item < array2[i]; }); console.log(result);

or simply using arrow functions.

 array1 = [12,13,14,15,16], array2 = [22,32,45,11,7] result = array1.map((item, i) => item < array2[i]); console.log(result);

If you want to return 1 or 0 values you can use + operator in order to force the result to number primitive type.

result = array1.map(function(item, i){
  return + (item < array2[i]);
});

If you want to receive array with boolean values which indicates if values are lower or higher try this:

var result = [];
for(var i = 0; i < array1.length;i++){
    result.push(array1[i] < array2[i]);
}

Try this:

  array1 = [12,13,14,15,16];
  array2 = [22,32,45,11,7];
  for(var x = 0; x < array1.length; x++) {
      if(array1[x] < array2[x]) {
          //do something
      }

  }

If I understood what you mean with your question this is called lexicographical comparison and is built-in for arrays in other languages (for example Python or C++).

In Javascript is present for strings, but you've to implement it yourself for arrays with something like

// lexical less-than-or-equal
function lex_leq(a, b) {
    let i = 0, na = a.length, nb = b.length, n = Math.min(na, nb);
    while (i<n && a[i] === b[i]) i++; // skip over equals
    return i === na || (i !== nb && a[i] < b[i]);
}

Other orderings can be computed by similar code or reusing the same implementation... for example (a<b) is the equivalent to !(b<=a) .

a1 = [12,13,14,15,16]
a2 = [22,32,45,11,7]
result = a1.map(function(item, i){
return item < a2[i];
});
console.log(result);

Try this solution. This will tell you which index doesn't match.

 var array1 = [12,13,14,15,16]; var array2 = [12,13,14,15,34]; function compareArray(arr1, arr2) { if(arr1.length !== arr2.length) return false; return arr1.reduce(function(acc, val, index) { acc.push(val === arr2[index]); return acc; }, []); } var response = compareArray(array1, array2); console.log(response);

 array1 = [12,13,14,15,16] array2 = [22,32,45,11,7] result = [] array1.map(function(item, i){ result[i] = item < array2[i]; }); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM