1

Can anyone guide me in deleting an object from array of objects in javascript

Here's my javascript code

<script>
  var line  = {lines:[]};

  function change(num){
    line.lines.push({"linechange":num});
  }
</script>

Here num is some integer value, Is there a way to delete the pushed object based on the value of num?

Kashyap
  • 4,400
  • 20
  • 24
Sumanth Udupa
  • 91
  • 2
  • 11
  • 2
    Did you try anything after having searched ? What's the problem ? Hint: look for the index, then delete the element at the given index. Or if you can afford a different array object, filter it. – Denys Séguret Sep 03 '15 at 06:50
  • [Array.prototype.filter()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) can help you. – Satpal Sep 03 '15 at 06:51
  • @Satpal Depends: it's important to note that filter doesn't remove an element from an array but gives a **new** array. – Denys Séguret Sep 03 '15 at 06:51
  • @DenysSéguret, Thats why in I used `can` and `line.lines = line.lines.filter(function( obj ) { return obj.linechange !== someVariable; })` will do – Satpal Sep 03 '15 at 06:54
  • @DenysSéguret hi , is there a way to do "look for the index" without for loop ? – user8244016 Aug 25 '17 at 20:03
  • 1
    @user8244016 yes there are. Search for "javascript array functions mdn". – Denys Séguret Aug 25 '17 at 20:04
  • @DenysSéguret thank you ,I used `.findIndex` and in the inner function I put `element.property=mydesiredvalue;`, – user8244016 Aug 25 '17 at 20:47

1 Answers1

0

Click here: https://stackoverflow.com/search?q=javascript+delete+from+array

Delete in this case will only set the element as undefined:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray
  [undefined, "b", "c", "d"]

Splice actually removes the element from the array:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]

A simple search and you got this by yourself. Reference: Deleting array elements in JavaScript - delete vs splice

Community
  • 1
  • 1
  • The above have different outcomes, but **both** remove elements from the array. In the first case, the *0* property is deleted and no other property is affected. This missing property is represented as *undefined*, but it doesn't exist (try `myArray.hasOwnProperty('0')`). In the second example, *splice* not only removes the members, but shifts all subsequent indexes to "fill" the empty space created. So when *0* and *1* are removed, *2* and *3* are shifted down to become *0* and *1*. – RobG Sep 03 '15 at 07:17