Say I have two arrays of objects. Like
var name = [
{ name : 'john' },
{ name : 'doe' }
]
var name2 = [
{ name : 'john' },
{ name : 'does' }
]
And I want to check if a name in the first array is the same as a name in the second array and return a response. I will do this below
for(var i = 0; i < name.length; i++) {
for(var j = 0; j < name2.length; j++) {
if(name[i].name === name2[j].name) {
console.log('good')
} else {
console.log('bad');
}
}
}
The above code would give the following result
good
bad
bad
bad
How do I achieve the same result without using a nested for loop?
I tried using forEach to loop through at once. Like
name.forEach(function(value, index) {
if(value.name === name2[index].name) {
console.log('good');
}
console.log('bad')
});
But this doesn't work and gives issues when they are arrays of different lengths.
All my research lead to using filter, map, reduce... methods. I want to achieve this using just for loops only. Thanks.
From
I tried using
forEach. But this doesn't work and gives issues when they are arrays of different lengths.
I gather you want to compare both arrays irrespective of the length. So, you can get the maximum length out of 2 arrays using Math.max. Then, loop through and check if the 2 arrays have the same value at each index
The condition name1[i] && name2[i] checks for undefined when the smaller array doesn't have a value at the specified index.
var name1 = [
{ name : 'john' },
{ name : 'doe' }
]
var name2 = [
{ name : 'john' },
{ name : 'does' },
{ name : 'jane' }
]
var maxLength = Math.max(name1.length, name2.length);
for (var i = 0; i < maxLength; i++) {
if (name1[i] && name2[i] && name1[i].name === name2[i].name)
console.log("good")
else
console.log("bad")
}
You can try the following code:
var arr = [
{ name : 'john' },
{ name : 'doe' }
]
var arr2 = [
{ name : 'john' },
{ name : 'peter' },
{ name : 'doe' }
]
var i = 0, length = Math.min(arr.length, arr2.length);
for(i; i < length; i++) {
if(arr[i].name === arr2[i].name) {
console.log('good')
} else {
console.log('bad');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With