1

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']].

3
  • kindly google for more sub tasks in your holistic task, e.g- how to compare string in java script and how to iterate over multi-dimentional arrays in javascript. Hope this will help. Commented Aug 26, 2018 at 7:00
  • btw, where do you get public from? Commented Aug 26, 2018 at 7:32
  • 1
    I use typescript class. So there i define the method as public. Commented Aug 26, 2018 at 7:41

3 Answers 3

1

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');
Sign up to request clarification or add additional context in comments.

2 Comments

Notice that this solution only good for 2 level depth - may be better to handle deeper levels also - or at least mention that in the answer
@DavidWinder According to the question, I don't think need to mention anything :) but of course making it generic would be efficient
0

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

Comments

0

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"]]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.