I am new to using recursion so I just want to know, if I want to know the index of an array element, by using recursion (Javascript). Is this the right way, or there is a better way?
let arr = [1, 2, 3, 4]
function search(arr, item) {
const searchIndex = (array, elem, index = 0) => {
if (array.length === 0) return -1
if (array[0] === elem) return index
return searchIndex(array.slice(1), elem, index)
}
return searchIndex(arr, item)
}
console.log(search(arr, 4)) // output should be 3
CodePudding user response:
You could change the arguments a bit and add index and hand over the complete array.
function search(array, item, i = 0) {
if (i >= array.length) return -1;
if (array[i] === item) return i;
return search(array, item, i 1);
}
let arr = [1, 2, 3, 4];
console.log(search(arr, 4)) // 3
console.log(search(arr, 8)) // -1
console.log(search([], 4)) // -1
An approach without an additional variable, but with slicing the array.
function search(array, item) {
if (!array.length) return -1;
if (array[0] === item) return 0;
return search(array.slice(1), item) 1 || -1;
}
let arr = [1, 2, 3, 4, 5];
console.log(search(arr, 1)) // 0
console.log(search(arr, 2)) // 1
console.log(search(arr, 3)) // 2
console.log(search(arr, 4)) // 3
console.log(search(arr, 5)) // 4
console.log(search(arr, 8)) // -1
console.log(search([], 4)) // -1
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
Why not using Array.prototype.indexOf()?
Check more here
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
let arr = [1, 2, 3, 4]
console.log(arr.indexOf(4))
CodePudding user response:
const arr = ['1', '2', '3','4']
const index = arr.indexOf('4');
console.log(index)
//index is `3`
