Reputation: 33
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
Upvotes: 1
Views: 3291
Reputation: 48367
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]);
});
Upvotes: 8
Reputation: 4046
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);
Upvotes: 0
Reputation: 718
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);
Upvotes: 0
Reputation: 11
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);
Upvotes: 0
Reputation: 114481
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)
.
Upvotes: 0
Reputation: 333
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]);
}
Upvotes: 2
Reputation: 149
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
}
}
Upvotes: 1