Home > Back-end >  How to append deleted from array elements by slice method?
How to append deleted from array elements by slice method?

Time:06-29

How to delete elements from start of array and append them into end ? enter image description here

  const ImageArray = [i1,i2,i3,i4,i5]

  const clickHandler = (index: number) => {
        let start = ImageArray.slice(index)
        let end = ImageArray....
        let result = start.concat(end)
        return result
    }

    {ImageArray.map((image, index) => (
                <div
                    onClick={() => clickHandler(index)}
                    key={index} style={{backgroundImage: 'url(' image ')'}}
                />
            ))}

P.S. It's not necessary to use slice method

CodePudding user response:

With x being the index clicked :

const arr = [0,1,2,3,4];
const newArr = [...arr.slice(x-1), ...arr.slice(0, x-1)]

CodePudding user response:

You can do:

const arr = ['i1','i2','i3','i4','i5']
const clickHandler = i => [...arr.slice(i), ...arr.slice(0, i)]

console.log('i3:', clickHandler(2)) // Clicked: 'i3'

CodePudding user response:

Your function is designed to return a new array, but the place where you call the function is not doing anything with the returned value.

I assume you want to mutate ImageArray. In that case use splice to delete the first part, and push to append that same part at the end:

const clickHandler = (index: number) => {
    ImageArray.push(...ImageArray.splice(0, index));
};

CodePudding user response:

You can try splice instead

const clickHandler = (index) => ImageArray.push(...ImageArray.splice(0, index)) 

In case if you are working with a state and doesn't want to mutate original array, try to spread ImageArray to make not deep copy of it

const clickHandler = (index) => {
   const arrCopy = [...ImageArray];
   arrCopy.push(...arrCopy.splice(0, index));
   return arrCopy;
}

CodePudding user response:

 array.splice(index).concat(array.splice(array.length - index))
  • Related