Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Check if an array contains only specified values

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]));
like image 998
gigs Avatar asked May 06 '18 14:05

gigs


People also ask

How do you check if an array contains a specific value in JavaScript?

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.

How do you check if an array contains a set of values?

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.

How do you check if an array contains a specific string?

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.


2 Answers

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]));
like image 110
Mihai Alexandru-Ionut Avatar answered Nov 15 '22 12:11

Mihai Alexandru-Ionut


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.

like image 42
Redu Avatar answered Nov 15 '22 12:11

Redu