My goal is to search for a specific item in an array called idarray
and loop through it until I find a value that is not equal to -1
. Once I find that value, I want to use the index to retrieve the corresponding value from another array called array
.
To accomplish this, I can use various iteration methods like for
, while
, or forEach
. In this case, I have two arrays: idarray
and array
. I have successfully implemented a process to determine the next data in the array and stop when reaching the final value. I can retrieve the next data as long as the corresponding id
is not -1
.
Here is my current implementation:
var item_tosearch = 0;
var idarray = [-1, 2, -1, 4, -1]
var array = [3, 2, 1, 0, 7];
var index = array.indexOf(item_tosearch);
if (index > -1) {
var res = array.slice(index);
}
if (res != undefined) {
for (let i = 0; i < res.length; i++) {
if (res[i + 1] != undefined) {
if (idarray[index + 1] == -1) {
if (res[i + 2] != undefined) {
console.log("Next = " + res[i + 2]);
break;
} else {
console.log("Final index");
break;
}
} else {
console.log("Next = " + res[i + 1]);
break;
}
} else {
console.log("Final index");
}
}
} else {
console.log('data not found');
}
I would like to know if there are any ways to improve this method.
Any advice is appreciated.
Clarification:
Imagine we have the following arrays:
idarray = [-1, 2, -1, 4, 1]; array = [3, 2, 1, 0, 7];
If I search for the value 2 in the idarray
, I expect to receive 0 as the returned value, as it is the next item without -1
in the id.
In another scenario:
idarray = [-1, 2, -1, -1, 1]; array = [3, 2, 1, 0, 7];
If I search for the value 2 in the idarray
, I expect to receive 7 as the returned value, as it is the next item without -1
in the id.
However, if the idarray is [-1, 2, -1, -1, -1] and I search for the value 2, I expect "final index" to be returned, as there are no more items without -1
as the id.
I have tried another iteration method to fetch the desired results:
var item_tosearch = 2;
var idarray = [-1, 2, -1, -1, -1]
var array = [3, 2, 1, 0, 7];
var index = array.indexOf(item_tosearch);
if (index > -1) {
var res = array.slice(index);
}
if (res != undefined) {
for (let i = 0; i < res.length; i++) {
if (res[i + 1] != undefined) {
if (idarray[index + 1] == -1) {
for (let j = i + 1; j < res.length - i; j++) {
if (res[j + 1] != undefined) { // fetch if still got data with id != -1
console.log("Next = " + res[j + 1]); // should show next item without -1 in id
break;
} else {
console.log("Final index"); // reach end of array
break;
}
}
} else {
console.log("Next = " + res[i + 1]); // should show next item without -1 in id
break;
}
} else {
console.log("Final index"); // reach end of array
}
}
} else {
console.log('data not found');
}