I wrote the following code, which has failed my test as I did not get the expected output [1, 2, 4]
.
const removeFromArray = function(array,...removeThis) {
for (let i=0;i<removeThis.length;i++){
array.splice(array.indexOf(removeThis),1);
}
return array;
};
removeFromArray([1, 2, 3, 4], 3)
To debug, I tried printing the individual variables to the console. The results are as follows:
removeThis.length
returns 1 (this works)removeThis
returns[3]
array.indexOf(removeThis)
returns -1 (this does not work)
From the docs:
The indexOf() method of Array instances returns the first index at which a given element can be found in the array, or -1 if it is not present.
I’m not sure why my indexOf() is not working and how I can fix this piece of code to get the expected output of [1,2,4].
My current output is [1,2,3].
EDIT: This is the full challenge statement, which involves passing all the tests
const removeFromArray = require('./removeFromArray')
describe('removeFromArray', () => {
test('removes a single value', () => {
expect(removeFromArray([1, 2, 3, 4], 3)).toEqual([1, 2, 4]);
});
test('removes multiple values', () => {
expect(removeFromArray([1, 2, 3, 4], 3, 2)).toEqual([1, 4]);
});
test('removes multiple of the same value', () => {
expect(removeFromArray([1, 2, 2, 3], 2)).toEqual([1, 3]);
});
test('ignores non present values', () => {
expect(removeFromArray([1, 2, 3, 4], 7, "tacos")).toEqual([1, 2, 3, 4]);
});
test('ignores non present values, but still works', () => {
expect(removeFromArray([1, 2, 3, 4], 7, 2)).toEqual([1, 3, 4]);
});
test('can remove all values', () => {
expect(removeFromArray([1, 2, 3, 4], 1, 2, 3, 4)).toEqual([]);
});
test('works with strings', () => {
expect(removeFromArray(["hey", 2, 3, "ho"], "hey", 3)).toEqual([2, "ho"]);
});
test('only removes same type', () => {
expect(removeFromArray([1, 2, 3], "1", 3)).toEqual([1, 2]);
});
});
2
Answers
There are these issues:
removeThis
is an array, as you have defined the parameter list with rest parameter syntax.indexOf
does not expect an array as argument. Maybe you intended to doindexOf(removeThis[i])
?If that problem is fixed, then only the first occurrence of the value will be removed. So this would not be good enough if the array can have multiple instances of the value to be removed.
It would remove the wrong value when the value to be removed does not occur at all in the array. In that case
indexOf
returns -1, and passing that as argument tosplice
will remove the last element of the array.There is a handy array method,
filter
, that was invented for returning an array with values that meet some condition. This is a good use case for using it:For large inputs (many parameters) this will be not the most efficient. If large inputs are possible, then create a
Set
of the values to be removed: