How to Remove Specific Element From An Array
In this example, you will learn to write a JavaScript program that will remove a specific element from an array.
Example 1 : Using For Loop Remove Element From Array
function removeElementFromArray(array, n) {
const newArray = [];
for ( let i = 0; i < array.length; i++) {
if(array[i] !== n) {
newArray.push(array[i]);
}
}
return newArray;
}
const elements = [1, 2, 3, 4, 5];
const result = removeElementFromArray(elements, 4);
console.log(result);
Output
[1,2,3,5]
In the above program, an element 4 is removed from an array using a for loop.
Example 2 : Using Array.splice() Remove Element From Array
const elements = [1, 2, 3, 4, 5];
//remove element 3
const result = elements.splice(2,1);
console.log(elements);
Output
[1, 2, 4, 5]
In the above program, an element 3 is removed from an array using a splice() method.
Comments
Post a Comment