Reputation: 41
I need to write a function that will delete the number or item entered in the input box. Heres what I have so far...
const my_arr = [1, 2, 3, 9]
function my_set_remove(my_arr, value) {
let result = [];
for (let i = 0; i < my_arr.length; i++) {
result = my_arr[i];
if (my_arr[i] == value) {
let new_arr = my_arr.pop[i];
return new_arr;
}
}
}
console.log(my_set_remove(my_arr, 9));
When I console.log it says undefined. Thanks in advance for your help
Upvotes: 1
Views: 62
Reputation: 183
ES6 reduce for solution
const my_arr = [1, 2, 3, 9]
function my_set_remove(my_arr, value){
return my_arr.reduce((acc, rec) => {
if (rec !== value) {
return acc.concat(rec)
}
return acc
},[])
}
console.log(my_set_remove(my_arr, 9 ))
Upvotes: 0
Reputation: 73
Using filter seems to be what you need:
const my_arr = [1, 2, 3, 9]
function my_set_remove(my_arr, value) {
return my_arr.filter((original_val) => original_val !== value)
}
console.log(my_set_remove(my_arr, 9));
Upvotes: 0
Reputation: 4241
From your comment you say:
This is for a class, so I am limited on what I can use. Im only allowed .length, .pop and .push, nothing else
So with that in mind, I try to stick to what you started with and make it work (although there are plenty of other ways to do it too):
you just need to push all items from your input array to your output/result array that do not equal your value you want to remove, and then at the end return that output/result array. Your input array remains unchanged.
Any questions, let me know.
const my_arr = [1, 2, 3, 9]
function my_set_remove(my_arr, value) {
let result = [];
for (let i = 0; i < my_arr.length; i++) {
if (my_arr[i] != value) {
result.push(my_arr[i]);
}
}
return result;
}
console.log(my_set_remove(my_arr, 9));
Output:
[1, 2, 3]
Upvotes: 1