Home > DeveloperSection > Forums > What is Object Splicing Array?
Tom Cruser
Tom Cruser

Total Post:28

Points:196
Posted on    November-24-2014 10:05 PM

 JavaScript JQuery  Array 
Ratings:


 1 Reply(s)
 546  View(s)
Rate this:

In my application i want to splice objects from an array upon matching, I am using lodash function for splicing like as shown below, unfortunately the json is not splicing correctly,

Can anyone give me some suggestion for this issue

var arr = [{

    name: 'kamlakar',

    id: 1001

}, {

    name: 'kamlakar',

    id: 1001

}];

 

var result = _.without(arr, _.findWhere(arr, {name: 'kamlakar'}));

console.log(JSON.stringify(result));

Expected result

[]

Actual Result

[{"name":"kamlakar","id":1001}]

Update 1

Even using normal JavaScript way also giving the same output

for(var i = 0; i < arr.length; i++) {

    var obj = arr[i];

 

    if(obj.name === 'kamlakar') {

        arr.splice(i, 1);

    }

}



Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    November-25-2014 2:10 AM

#1

var arr = [{

    name: 'Kamlakar',

    id: 1001

}, {

    name: 'Kamlakar',

    id: 1001

}];

var result = _.rest(arr, function (el) {

  return el.name === 'kamlakar';

});

console.log(JSON.stringify(result)); // "[]"

#2

var arr = [{

    name: 'kamlakar',

    id: 1001

}, {

    name: 'kamlakar',

    id: 1001

}, {

  name: 'Rohit',

  id: 1002

}];

var result = _.rest(arr, function (e) {

  return e.name === 'kamlakar';

});

console.log(JSON.stringify(result)); // "[{\"name\":\"Rohit\",\"id\":1002}]"

// 3 also you can use _.filter if you do not want slice of array...

var result = _.filter(arr, function (e) {

  return e.name !== 'kamlakar';

});

console.log(JSON.stringify(result)); // "[{\"name\":\"Rohit\",\"id\":1002}]"


Don't want to miss updates? Please click the below button!

Follow MindStick