Reputation: 1
so, i have the linear search implemented in JS and i tried to implement it with ternary operator but the it returns -1...
I have this code:
const numbers = [1, 2, 3, 4, 5];
function linear(arr, value) {
for (let i = 0; i < arr.length; ++i) {
return (arr[i] === value ? i : -1);
}
}
when I run console.log(linear(numbers, 3))
, it gives me -1 as a result, and 3 is in my array. Anyone ?
Also, when i try with forEach it returns undefined code here:
function linearSearch(arr, value) {
arr.forEach((num, index) => {
return (num === value ? index : -1);
})
}
const res = linearSearch(numbers, 3);
console.log(res);
Upvotes: 0
Views: 181
Reputation: 13289
The problem is that you are returning at the first loop of your circle, you should change your algorithm like this:
const numbers = [1, 2, 3, 4, 5];
function linear(arr, value) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === value) {
return i;
}
}
return -1;
}
console.log(linear(numbers, 3));
However, if you don't need an explicit implementation of the algorithm, a much cleaner version of this would be by using the built-in indexOf
function:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.indexOf(3));
Upvotes: 1
Reputation: 1529
In your first example, you return too often. Meaning, you never get further than your first iteration, because then you either return 0 (if the first element matches) or -1 if it doesn't. Here's a proposed fix:
const numbers = [1, 2, 3, 4, 5];
function linear(arr, value) {
for (let i = 0; i < arr.length; ++i) {
if(arr[i] === value) {
return i
}
}
return -1
}
In the second example, you do the same thing, but in addition to this, it seems you don't fully understand how the callback in .forEach(callback)
works (meaning that if you return something inside a .forEach
, nothing happens to that returned value). I don't think a .forEach
is the way to go here, but if you really wish to use it, you could do it like so:
function linear2(arr, value) {
let indexMatch = -1
arr.forEach((num, index) => {
if(value === num) {
indexMatch = index
}
}
return indexMatch
}
Upvotes: 0