What is the quickest way to compare two arrays and return a third array containing the values from array2
where the associated values from array1
are true
?
const array1 = [true, false, false, true];
const array2 = ['a', 'b', 'c', 'd'];
The result should be:
const result = ['a', 'd'];
Java Arrays class provides the equals () method to compare two arrays. It iterates over each value of an array and compares the elements using the equals () method. It parses two arrays a1 and a2 that are to compare. The method returns true if arrays are equal, else returns false.
It will never return false because it always returns a string value. Also, you are always returning after comparing only the first item in both arrays. One problem I see is the else statement. What you're currently saying is if the current element in each array is the same as the other, then the arrays the same.
Compare Two Arrays in Python Using the numpy.array_equal () Method. The numpy.array_equal (a1, a2, equal_nan=False) takes two arrays a1 and a2 as input and returns True if both arrays have the same shape and elements, and the method returns False otherwise.
Check if two arrays are equal or not. Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though. Note : If there are repetitions, then counts...
Use filter
.
const array1 = [true, false, false, true];
const array2 = ['a', 'b', 'c', 'd'];
const res = array2.filter((_, i) => array1[i]);
console.log(res);
ES5 syntax:
var array1 = [true, false, false, true];
var array2 = ['a', 'b', 'c', 'd'];
var res = array2.filter(function(_, i) {
return array1[i];
});
console.log(res);
Filter
function is slower than for loop. The quicker option is to use for loop with or without ternary operator.. It is faster than the filter
function.
I've include a code snippet that shows how long each option takes.
const array1 = [true, false, false, true];
const array2 = ['a', 'b', 'c', 'd'];
// filter
console.time('filter');
const result1 = array2.filter((_, i) => array1[i]);
console.timeEnd('filter');
console.log(result1);
// for loop with ternary operator
console.time('forLoopWithTernary');
const result2 = [];
for(let i = 0; i < array2.length; i++){
(array1[i]) ? result2.push(array2[i]) : null;
}
console.timeEnd('forLoopWithTernary');
console.log(result2);
// for loop w/o ternary operator
console.time('forLoopWithoutTernary');
const result3 = [];
for(let i = 0; i < array2.length; i++){
if(array1[i])
result3.push(array2[i]);
}
console.timeEnd('forLoopWithoutTernary');
console.log(result3);
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