0

The way I am removing elements from my array right now is this

var indexToRemove = newSections.indexOf(newSections.find((section) => section.id === parseInt(sectionId)));
newSections.splice(indexToRemove, 1);

However, I want to be able to remove my elements as such.

array.remove(element)

How can I accomplish something like this?

nanomosfet
  • 131
  • 9
  • 1
    check this [question](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – Marcelo Origoni Dec 17 '17 at 03:06
  • 1
    Not really. You can use lodash which will make your code more concise. – Eric Guan Dec 17 '17 at 03:08
  • Is it possible to extend the array class? @EricGuan – nanomosfet Dec 17 '17 at 03:16
  • 1
    @TimmyZubkisSearcy Extending built-in objects is generally not a good idea. https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice – Brett Jackson Dec 17 '17 at 03:17
  • Possible duplicate of [How do I remove a particular element from an array in JavaScript?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – Stephen Ostermiller Dec 17 '17 at 10:42

3 Answers3

2

There isn't an API to do such a thing in place, but you can do something similar with Array.filter.

let words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];

words = words.filter(word => word != "spray");

In the example above, words will not contain the word spray.

Brett Jackson
  • 421
  • 7
  • 18
  • 1
    ie, `newSections = newSections.filter(section => section.id !== parseInt(sectionId))` – Faust Dec 17 '17 at 03:20
1

If you want to do the deletion in place, you can do a little better with reduce:

var indexToRemove = newSections.reduce(
    (acc,section,index) =>
        (acc === null && section.id === parseInt(sectionId) ? index : acc),
    null);
if (indexToRemove !== null)
    newSections.splice(indexToRemove, 1);

So you array is parsed only once.

Otherwise I would prefer the answer with find

RaphaMex
  • 2,509
  • 10
  • 25
1

Assuming the following

sections = [
    {id: 1, name: 'section 1'},
    {id: 2, name: 'section 2'},
    {id: 3, name: 'section 3'}
]

Define simple function

function removeSection(sections, sectionIdToRemove) {
  return sections.filter(s=>s.id != parseInt(sectionIdToRemove)
}

Use it

removeSection(sections, 1) // removes the second section

it is not recommended to add such a .remove method to the global Array Object.

Ahmed Ayoub
  • 482
  • 4
  • 12