WHAT IS OBJECT SPLICING ARRAY?

Tom Cruser

Total Post:28

Points:196
Posted by  Tom Cruser
 886  View(s)
Ratings:
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);

    }

}

  1. Kamlakar Singh

    Post:194

    Points:1396
    Re: What is Object Splicing Array?

    #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}]"

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!