w3resource

JavaScript: Remove a specific element from an array

JavaScript Array: Exercise-31 with Solution

Remove Specific Element

Write a JavaScript function to remove a specific element from an array.

Test data:
console.log(remove_array_element([2, 5, 9, 6], 5));
[2, 9, 6]

Visual Presentation:

JavaScript: Remove a specific element from an array

Sample Solution:

JavaScript Code:

// Function to remove an element from an array
function remove_array_element(array, n) {
  // Find the index of the element 'n' in the array
  var index = array.indexOf(n);
  
  // Check if the element exists in the array (index greater than -1)
  if (index > -1) {
    // Remove one element at the found index
    array.splice(index, 1);
  }
  
  // Return the modified array
  return array;
}

// Output the result of removing element '5' from the array [2, 5, 9, 6]
console.log(remove_array_element([2, 5, 9, 6], 5));

Output:

[2,9,6]

Flowchart:

Flowchart: JavaScript: Remove a specific element from an array

ES6 Version:

// Function to remove an element from an array
const remove_array_element = (array, n) => {
  // Find the index of the element 'n' in the array
  const index = array.indexOf(n);

  // Check if the element exists in the array (index greater than -1)
  if (index > -1) {
    // Remove one element at the found index
    array.splice(index, 1);
  }

  // Return the modified array
  return array;
};

// Output the result of removing element '5' from the array [2, 5, 9, 6]
console.log(remove_array_element([2, 5, 9, 6], 5));

Live Demo:


See the Pen JavaScript - Remove a specific element from an array- array-ex- 31 by w3resource (@w3resource) on CodePen.

For more Practice: Solve these Related Problems:

  • Write a JavaScript function that removes a specific element from an array using the filter() method.
  • Write a JavaScript function that uses splice() to remove the first occurrence of a specified element.
  • Write a JavaScript function that removes all occurrences of a given element and returns the updated array.
  • Write a JavaScript function that checks for the existence of the element before attempting removal and handles errors.

Go to:


PREV : Merge Arrays Without Duplicates.
NEXT : Find Element in Array.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.