skip to Main Content

In an array I want to find the index of a value and then remove that value. The constraint is that I have to use core JavaScript without any frameworks.

let array = [9,8,7,6,5,4,3,2,1];

How can I find the index of ‘4’ and remove it from the array using core JavaScript?

2

Answers


  1. let array = [9, 8, 7, 6, 5, 4, 3, 2, 1];
    
    // Find the index of the value '4'
    let index = array.indexOf(4);
    
    // array is valid length
    if (index !== -1) {
      // Remove the value at index
      array.splice(index, 1);
    }
    
    console.log(array);
    Login or Signup to reply.
  2. You don’t need to find the value from Index 4 in order to remove it, you can just blindly remove it using Array.splice()

    let array = [9,8,7,6,5,4,3,2,1];
    const indexFound = array.findIndex(el => el === 4);
    console.log('Value at index 4 found:', indexFound);
    
    array.splice(4);
    
    console.log(array)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search