w3resource

JavaScript: Remove a specific element from an array

JavaScript Array: Exercise-31 with Solution

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));

Sample 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.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to merge two arrays and removes all duplicates elements.
Next: Write a JavaScript function to find an array contains a specific element.

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.