Reputation: 415
The Question
Write a function that gets a sequence and value and returns true/false depending on whether the variable exists in a multidimensional sequence.
Example:
locate(['a','b',['c','d',['e']]],'e'); // should return true
locate(['a','b',['c','d',['e']]],'a'); // should return true
locate(['a','b',['c','d',['e']]],'f'); // should return false
My Solution Seems To Work, but Code Wars says: "arr.flat is not a function.
I use the free code camp browser to run and test my code, and my console logs suggested I had it working, but Code Wars was saying arr.flat is not a function. Here is my code:
var locate = function(arr, value){
let count = 0;
arr.flat().map((item)=>{
value == item ? count++ : count;
});
return count > 0 ? true : false;
}
My Question
Is my code correct or not? If not, what's wrong. If so, why might Code Wars be throwing an error?
Upvotes: 1
Views: 470
Reputation: 18249
You don't actually need .flat
for this (although that would allow the most elegant solution of const locate = (arr, value) => arr.flat().includes(value);
). Here's a simple recursive solution using an ordinary for
loop:
const locate = function(arr, value) {
for(let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i]) {
if (locate(arr[i], value) {
return true;
}
}
if (arr[i] === value) {
return true;
}
}
return false;
}
Upvotes: 1
Reputation: 11001
Since flat
is supported in your environment, Write own flat method and use the includes
const flat = (arr, res = []) => (
arr.forEach((item) =>
Array.isArray(item) ? flat(item, res) : res.push(item)
),
res
);
const locate = (arr, value) => flat(arr).includes(value);
console.log(locate(["a", "b", ["c", "d", ["e"]]], "e"));
console.log(locate(["a", "b", ["c", "d", ["e"]]], "a"));
console.log(locate(["a", "b", ["c", "d", ["e"]]], "f"));
Upvotes: 1
Reputation: 386550
You could take a recursive approach with a short circuit on find.
function locate(array, value) {
return array.some(v => Array.isArray(v) && locate(v, value) || v === value);
}
console.log(locate(['a', 'b', ['c', 'd', ['e']]], 'e')); // true
console.log(locate(['a', 'b', ['c', 'd', ['e']]], 'a')); // true
console.log(locate(['a', 'b', ['c', 'd', ['e']]], 'f')); // false
Upvotes: 1
Reputation: 5205
It seems to be working here. So chances are the browser on which you're testing doesn't support flat()
var locate = function(arr, value){
let count = 0;
arr.flat().map((item)=>{
value == item ? count++ : count;
});
return count > 0 ? true : false;
}
console.log(locate(['a','b',['c','d',['e']]],'e')); // should return true
console.log(locate(['a','b',['c','d',['e']]],'a')); // should return true
console.log(locate(['a','b',['c','d',['e']]],'f')); // should return false
Upvotes: 1