1

I have a "rails" array within my constructor which are imported components:

import MusicRail from '../../components/MusicRail';
import GamesRail from '../../components/GamesRail';
import MoviesRail from '../../components/MoviesRail';

constructor(props) {
   super(props);

   this.rails = [
      MusicRail,
     GamesRail,
     MoviesRail
  ]
}

How can I clone or duplicate the first and last objects to then push to the rails array? Can I use Object.assign() ?

I'm getting the first and last objects from the array like so:

const rails = this.rails;
const firstObject = this.rails[0];
const lastObject = this.rails.slice(-1)[0];

2 Answers 2

1

Object.assign has nothing to do with Array (at least in this scenario), you may want to try this.

const rails = this.rails;
const firstObject = this.rails[0];
const lastObject = this.rails.slice(-1)[0];
this.rails = [...rails, firstObject, lastObject]; 

and if you're trying to build an infinite slider.

this.rails = [lastObject, ...rails, firstObject]; 
Sign up to request clarification or add additional context in comments.

5 Comments

This is great! So my last question is, how can I push the clone of the first item to be last and then the clone of the last item be first? I'm trying to build an infinite slider.
@Littlee, Why not? Why Object.assign has nothing to do with Array?
Figured it out! Change the order of this.rails = [lastObject, ...rails, firstObject];
@Littlee Hey, I have a question - when I scroll to the last item which is a clone of the first in the array, I don't see the GamesRail after and so forth. You know like an infinite slider? Do you know how to go about this?
@Filth try this github.com/akiran/react-slick, if implementing it from scratch takes too much time. You may post another question, cuz answering in comment can't provide much details 😂
0

Use myArray.slice() or lodash method _.cloneDeep()

You can also use concat or spread operator:

let newArray = [
     ...arr
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.