splice explanation

PHOTO EMBED

Fri Apr 05 2024 02:05:28 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale #javascript #splice #slice #findindex

// remove element at certain index without changing original
let arr = [0,1,2,3,4,5]
let newArr = [...arr]
newArr.splice(1,1)//remove 1 element from index 1
console.log(arr) // [0,1,2,3,4,5]
console.log(newArr)// [0,2,3,4,5]



eg //


const comments = [
      { text: 'Love this!', id: 523423 },
      { text: 'Super good', id: 823423 },
      { text: 'You are the best', id: 2039842 },
      { text: 'Ramen is my fav food ever', id: 123523 },
      { text: 'Nice Nice Nice!', id: 542328 }
    ];



// Array.prototype.findIndex()
// Find the comment with this ID
   const commentIndex = comments.findIndex((item) => item.id === 823423)
    // delete the comment with the ID of 823423
    const commentsCopy = [...comments];
    commentsCopy.splice(1, commentIndex) //remove 1 element from index 1
    console.log(commentsCopy)


// or we can use slice from the start to the value and from the value to the end
const newComments = [
  ...comments.slice(1, commentIndex)
  ...comments.slice(commentIndex++)
]
    
content_copyCOPY