Sridhar Natuva
Sridhar Natuva

Reputation: 211

How to search for a string in array of arrays using javascript function

This function is able to search for a string in an array:

public checkElement( array ) {        
    for(var i = 0 ; i< array.length; i++) {
        if( array[i] == 'some_string' ) {
            return true;
        }      
    }
 }

How can i use array of arrays in the for loop? I want to pass this to a function that search a string with if condition.

Example input: array[['one','two'],['three','four'],['five','six']].

Upvotes: 1

Views: 2697

Answers (3)

FZs
FZs

Reputation: 18619

Try this code:

function checkElement(array){        
 for(value of array){
  if(value.includes("some string")){return true}
 }
 return false
}
console.log(checkElement([["one","two"],["three","four"],["five","six"]]))
console.log(checkElement([["one","two"],["three","four"],["five","some string"]]))

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191966

This is a recursive solution that checks if an item is an array, and if it is searches it for the string. It can handle multiple levels of nested arrays.

function checkElement(array, str) {
  var item;
  for (var i = 0; i < array.length; i++) {
    item = array[i];
    
    if (item === str || Array.isArray(item) && checkElement(item, str)) {
      return true;
    }
  }
  
  return false;
}

var arr = [['one','two'],['three','four'],['five','six']];

console.log(checkElement(arr, 'four')); // true
console.log(checkElement(arr, 'seven')); // false

And the same idea using Array.find():

const checkElement = (array, str) =>
  !!array.find((item) =>
    Array.isArray(item) ? checkElement(item, str) : item === str
  );

const arr = [['one','two'],['three','four'],['five','six']];

console.log(checkElement(arr, 'four')); // true
console.log(checkElement(arr, 'seven')); // false

Upvotes: 0

prabhatojha
prabhatojha

Reputation: 2085

You can try the "find" method instead

let arr = [['one','two'],['three','four'],['five','six']];

function searchInMultiDim(str) {
    return arr.find(t => { return t.find(i => i === str)}) && true;
}

searchInMultiDim('one');

Upvotes: 1

Related Questions