Search code examples
javascriptarrayssortingindexingarray-splice

Deleting specific index from a JavaScript array


I have a little code written where I am tracking indexes which I have successfully but finding difficulty removing them from the array so I do same with what I am left with.

 var v = [4, 7, 2,5, 3] 
 var f = []
 for (let i = 1; i < v.length; i += 2){
/*(point1)this line doesn't seem to work*/
 if (v[i] > v[i] - 1)
/*(point 2) Instead of console.log I want to delete every of v[i] */
console.log(v[i])

Output

7
5

Expected Output when v[I] is deleted

 v = [4,2,3]

Preferably I would like to do something like splice v[i] if v[i] > v[i] -1 and get back v as with the spliced elements.

I first tested point 1 with this similar logic in the command line and it worked but.....;

   if ((b[1] -1) > b[0]){console.log(b[2])}

Output

3
```

Solution

  • Build new array res by eliminating the unwanted elements from array v

    var v = [4, 7, 2, 5, 3];
    var res = [];
    res.push(v[0]);
    for (let i = 1; i < v.length; i += 1) {
      if (v[i - 1] > v[i]) {
        res.push(v[i]);
      }
    }
    
    console.log(res);