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']]
.
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');
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
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"]]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.