I have two arrays. The first array contains a bunch of values, while the second one is empty. I have a search function that checks and sees if the value is in the first array, if it is it stays in the array. However, if the value isn't in the array it needs to get taken out and put into the second array, until they clear the search and then all go back into the original array.
Lets say array1 = [0, 1]; Lets say array2 = [];
The problem I am having is after is searching, it will remove properly if I filter out the 1, but not properly if I filter out the 0.
For example:
`for (i=0; i<(array1.length); i++){
if (0 !== array1[i]){
array2.push(array1[i]);
array1.splice(i, 1);
}
}`
If I type 1 in my search array1 =[1] and array2 = [0] like it should work However, if I type 0 into my search array1 = [0,1] and array2=[] and it doesn't work.
Any idea why this is not working like how I thought it would?
If you're just trying to remove something from one array and put it in another, you could do that with two filters to simplify your code.
let array1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
let array2 = [ ];
document.querySelector('button').addEventListener('click', event => {
const searchvalue = event.target.previousElementSibling.value;
// The actual work:
array2 = array1.filter(i => i == searchvalue);
array1 = array1.filter(i => i != searchvalue);
console.log(array1, array2);
});
<input type="number" min="1" max="10" step="1" value="5"/>
<button>Search</button>