DEV Community

Discussion on: 20 Killer JavaScript One-Liners That’ll Save You Hours of Coding 🤯🔥

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

21) Delete a specific item from an array -
arr.splice(arr.indexOf(item_to_delete),1)

Example -
let arr = ["A","B","C","D","E"];

arr.splice(arr.indexOf("C"),1)

console.log(arr)//[ 'A', 'B', 'D', 'E' ]

Collapse
 
devdufutur profile image
Rudy Nappée

Or arr = arr.filter(i => i !== "C")

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

But i think using filter method to delete an element is heavy process as filter method returns a new array , suppose you are performing this action on 1000 Dom elements, it means if you remove 1 element using filter, other 999 element will rerender
On the other hand using splice method will remove the element from the original array directly

Thread Thread
 
marcelomartinez profile image
Marcelo Martínez

Talking about React, the other 999 elements won´t rerender because it keep track of them with a key and knows they haven´t changed.

Also, Reacts uses the Object.is(x, y) method to know when the state changed, and if you remove an array element using splice, React won´t rerender because it still is the reference to the same array even tho you modified it.

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

And for the Vanilla javascript?
Btw I use Event Propagation to remove Elements from DOM in Vanilla javascript

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Also if we splice the state of useState and then update the state with the spliced version using setState, will it make a difference?

Thread Thread
 
devdufutur profile image
Rudy Nappée

Don't mutate your state in React !
stackoverflow.com/questions/551785...

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Ohk thanks for this

 
devdufutur profile image
Rudy Nappée

What do you mean by rerender ?

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Like once in a project i mapped the Array item with HTML UI using method,
Then delete element with button click using filter method, What it was doing is refreshing the entire list of HTML element, like there is a update Dom method which sets the innerHTML of the list with the updated array
So it was doing a heavy operation with that filter array approach
Then i used the Event Propagation and find the element using closest() method of DOM, when we click on delete button of an element, it will find the closest parent element which holds that delete button and other Things, and then deleting that parent element using remove() method

Thread Thread
 
devdufutur profile image
Rudy Nappée

Actually with React you shouldn't mutate your state. If your keys are consistent it will not rerender your other elements. With filter, the objects identities doesn't change, only the array identity (it returns a new array containing the same objects).

Collapse
 
rammcodes profile image
Ram Maheshwari ♾️

Looks great, Thanks for sharing 🙌

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Or:

let arr = ["A","B","C","D","E"]
arr = Object.values(({[arr.indexOf('C')]:arr,...arr}=arr,arr))
console.log(arr)  //[ 'A', 'B', 'D', 'E' ]
Enter fullscreen mode Exit fullscreen mode

🤣🤣🤣

Gold star to the first person to fully explain how this works

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

It deletes an element lol 😂😂

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Makes you sound like a pirate reading that second line of code! Arrrrrr!

Arr

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

Well this is the best method i found to delete an element inside DOM as a Jr. Developer 😂😂
If it is wrong correct it 🥶

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Oh boy, this is gonna be fun. First of all, re-formatting the code a bit will make it a lot more readable:

Object.values(
  (
    {
      [arr.indexOf('C')]:arr,
      ...arr
    } = arr,
    arr
  )
)
Enter fullscreen mode Exit fullscreen mode

Starting from the outside, Object.values does what it says on the tin and returns the values of the object, so it's safe to assume whatever happens on the inside will return an object mapping some values to the array items except for the one to be deleted.

The inner pair of braces is a bit weird. I haven't checked this with the documentation, but from the looks of it, the form (exp_1, expr_2) will evaluate two expressions and return only the latter, so this block could be somewhat reshaped into something along these lines:

    {
      [arr.indexOf('C')]:arr,
      ...arr
    } = arr
    return arr
Enter fullscreen mode Exit fullscreen mode

if it was a function. So the code applies some de-structuring magic to the array, then hands it back to Object.values as mentioned above.

Now, for the de-structuring part, here's where the real magic happens.

The first access of arr inside square braces is just accessing the array for reading; it gets the index of the element to be deleted. The second two occurrences of arr can be thought of as "writing" access, as in these are making changes to the variable.

Looking at the components here:

({...foo} = bar) is a weirder way of writing foo = {...bar} but using destructuring. So what's happening there, on its own, is arr = {...arr}, meaning we get an array-like object copy of arr.

({[0]: foo} = [1, 2, 3]) is equivalent to foo = [1, 2, 3][0]

At this point, I'm still struggling to wrap my head around what actually happens here, but with a bit of testing, it looks like the rhs of the de-structuring assignment doesn't have to be the same variable, which makes for a much simpler example:

({[0]: arr, ...arr} = [1, 2, 3], arr)
Enter fullscreen mode Exit fullscreen mode

This somehow results in the object {1: 2, 2: 3}.

After some more testing, it looks like the first arr in this expression can be any other variable:

({0: _, ...arr} = [1, 2, 3], arr)
Enter fullscreen mode Exit fullscreen mode

Which now makes it a lot more obvious what's going on. The key 0 (in my example) is being de-structured into some throw-away variable, then the remaining key-value pairs are de-structured into arr. In the original code, this "throw-away" variable just happens to also be arr to save up on a let and to make the code a bit more confusing.


So, what ultimately happens is:

  1. The index of the value to delete is calculated
  2. The array is de-structured into a throw-away variable (key from 1.) and into arr (other keys)
  3. arr is passed into Object.values, returning all values of the array except the one to be deleted in the form of a new array.

There you go :)

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️