This answer would be a great place to start for understanding how to remove an item from an array.
Arrays in javascript are a type of object. Objects are keys and values.
If you want to a function that will take this array
[2, 4, 7, 2, 9, 4, 0, 3, 6, 2];
and return this array
[2, 4, 7, 2, 4, 0, 3, 6, 2];
You are technically manipulating more than just the value 9
at key 4
. You would be reassigning a new key to each value following the space the value 9
used to be in as well.
If you are trying to return an array that is filtered based on certain criteria, such as the number being 9, you could use the method .filter
(docs)
A brief overview of .filter
, the method has optional arguments and functionality that is beyond the scope of a brief overview, but to keep things short; the .filter
method takes a callback function as an argument. The callback function will be applied to each item in the array, with the item being passed as an argument. If the function returns true, the item will be returned in the result. If the function returns false, the item will not be returned in the result.
i.e.
console.log(
[2, 4, 7, 2, 9, 4, 0, 3, 6, 2]
.filter(number => number !== 9)
.toString()
);
/*styling console display -- not relevant to answer*/
.as-console-wrapper { max-height: 100% !important; top: 0; }
I used an anonymous arrow function as my callback function, number => number !== 9
, this is the equivalent of
function (number) {
return number !== 9
}
What happens is each item in the array is passed as an argument to my callback function. I am declaring the name of the variable where that argument will be passed is called number
. I am returning number !== 9
which will return true
so long as the number is not 9. This means each item will be checked to see if it is equal to 9, and if it is not, it will return true, making the final array returned filter out all values equal to 9. I will give you an example of another filter statement.
[2, 4, 7, 2, 9, 4, 0, 3, 6, 2].filter(
function( anyName ) {
if ( anyName === 9 ) return false;
if ( anyName === 3 ) return false;
if (anyName / 2 === 2) return false;
return true;
}
);
//returns [2, 7, 2, 0, 6, 2]
this filter returns false when an item is 9, 3, or when divided by 2 is 2 (i.e. 4)
The first example would however remove all instances of the value 9 in the array. If you only want to remove the first occurring 9 you could do this several ways.
You could use .findIndex
(docs) and remove the value by it's index.
i.e.
const arr1 = [2, 4, 7, 2, 9, 4, 0, 3, 6, 2];
const indexToRemove = arr1.findIndex(number => number === 9);
const processedArr = [
...arr1.slice(0, indexToRemove),
...arr1.slice(indexToRemove + 1, arr1.length)
];
console.log(processedArr.toString());
/*styling console display -- not relevant to answer*/
.as-console-wrapper { max-height: 100% !important; top: 0; }
hopefully this helps point you in the right direction- if you have more specific examples of your goal please update your question