How can I optimize a function that checks if an array contains only specified values not using hardcoded values?
Here is the function
function containOnly(value1, value2, array){
var result;
for(i = 0; i < array.length; i++){
if(array[i] != value1 && array[i] != value2){
result = 0;
break;
} else
result = 1;
}
if(result === 0)
return false;
else
return true;
}
console.log(containOnly(1, 2, [2,1,2]));
This function will return true if an array contains specified values. In this function I use if statement to compare two values but how can I use an array of values instead of variables if I want to use more than two values? For example:
console.log(containOnly([1, 2, 3], [2,1,2,3,5]));
JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
Using List contains() method. We can use Arrays class to get the list representation of the array. Then use the contains() method to check if the array contains the value.
To check if a string is contained in an array, call the indexOf method, passing it the string as a parameter. The indexOf method returns the index of the first occurrence of the string in the array, or -1 if the string is not contained in the array.
You can achieve your requirement using every
method by passing an arrow
function as argument.
The every() method tests whether all elements in the array pass the test implemented by the provided function.
function containsOnly(array1, array2){
return array2.every(elem => array1.includes(elem))
}
console.log(containsOnly([1, 2, 3], [2,1,2,3,5]));
console.log(containsOnly([1, 2], [2,1,2,1,1]));
Another solution is to use some
method.
function containsOnly(array1, array2){
return !array2.some(elem => !array1.includes(elem))
}
console.log(containsOnly([1, 2, 3], [2,1,2,3,5]));
console.log(containsOnly([1, 2], [2,1,2,1,1]));
You can simply &&
up .includes()
method.
var arr = [0,1,3,5,7,9,2,6,8,11,32,53,22,37,91,2,42],
values1 = [0,2,37,42],
values2 = [91,99,9],
checker = ([v,...vs], a) => v !== void 0 ? a.includes(v) && checker(vs, a)
: true;
console.log(checker(values1,arr));
console.log(checker(values2,arr));
This is also efficient than .reduce()
since it will stop recursing once the first false
value is obtained.
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