Juliver Galleto
Juliver Galleto

Reputation: 9037

remove array object by its index

I'm trying to remove an array object from an array. First, I loop to the array of objects and if that array match to the given filter, then remove that object. Below is what I've tried but unfortunately not working, any help, ideas, clues, suggestions, recommendations please?

$(document).ready(function(){
  
  var n_array = [{ 'name' : 'jason', 'age' : '24'},{ 'name' : 'jason2', 'age' : '20'}];

  console.log(n_array);
  
  for(var i = 0; i < n_array.length; i++){
   if(n_array[i].name==='jason'){
     n_array.splice(i,0);
   }
  }
  console.log(n_array);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Views: 52

Answers (4)

Roli Agrawal
Roli Agrawal

Reputation: 2466

Problem with yours code is splice syntax

splice syntax is: array.splice(index,howmany element going to delete,value_item1,.....,value_itemX);

In urs code you are using n_array.splice(i,0); so you are giving 0 element to delete.

Make it Like

var n_array = [{ 'name' : 'jason', 'age' : '24'},{ 'name' : 'jason2', 'age' : '20'}];

  console.log(n_array);

  for(var i = 0; i < n_array.length; i++){
   if(n_array[i].name==='jason2'){
     n_array.splice(i,1);
   }
  }
  console.log(n_array);

Hope it will help

Upvotes: 0

sandesh jadhav
sandesh jadhav

Reputation: 119

this may help you n_array.slice(i); replace this with n_array.splice(i, 1);

slice() method is used to select the elements from array

Upvotes: 0

vaso123
vaso123

Reputation: 12391

You can use delete.

Here is the reference to it, this is exactly what you looking for.

if (n_array[i].name === 'jason') {
    delete n_array[i].name;
}

The delete operator removes a property from an object.

Upvotes: 2

Tushar
Tushar

Reputation: 87203

  1. You need to use Array#splice and not Array#slice to remove element from array.

    n_array.splice(i, 1);
    

var n_array = [{
    'name': 'jason',
    'age': '24'
}, {
    'name': 'jason2',
    'age': '20'
}];

for (var i = 0; i < n_array.length; i++) {
    if (n_array[i].name === 'jason') {
        n_array.splice(i, 1);
    }
}
console.log(n_array);

  1. You can use Array#filter to remove an element from array.

    var n_array = [{
        'name': 'jason',
        'age': '24'
    }, {
        'name': 'jason2',
        'age': '20'
    }];
    
    n_array = n_array.filter(function(obj) {
        return obj.name !== 'jason';
    });
    console.log(n_array);
    

var n_array = [{
    'name': 'jason',
    'age': '24'
}, {
    'name': 'jason2',
    'age': '20'
}];

n_array = n_array.filter(function(obj) {
    return obj.name !== 'jason';
});
console.log(n_array);

Upvotes: 2

Related Questions