26

I want to skip the first in the .map function what I do now is this:

block.gallery.map((item, i) => (
       <div className="gallery-item" key={i}>
        { block.gallery.length > 4 && i !== 0 ?
          <div className="inner">
             <img src={block.gallery[i].images.thumbnail_sm} alt={block.title} srcSet={`${block.gallery[i].images.thumbnail_md} 1x, ${block.gallery[i].images.thumbnail_lg} 2x`} className="img-fluid" title="" />
             <div className="img-overlay">
               <span className="img-overlay-body">{ block.gallery.length - 4 }+ <span className="hidden-xs">Foto's</span></span>
             </div>
           </div>
           :
           <img src="http://placehold.it/800x538" alt="" className="img-fluid" title="" />
          }
3
  • Why you are using map here as you are not returning anything. To loop the array you can use forEach and to skip the first item you can check if (i > 0) Commented Nov 18, 2016 at 14:37
  • @Aruna the thing being returned is the <div className="gallery-item"> and everything it contains. Commented Nov 18, 2016 at 14:44
  • It would help to update your question given that your code no longer uses .map Commented Nov 18, 2016 at 14:45

2 Answers 2

79

So slice it to skip the first

block.gallery.slice(1).map(...)

You also need to reference the item passed into map, not using the index with the orginal array.

block.gallery[i].images.thumbnail_sm

should be

item.images.thumbnail_sm
Sign up to request clarification or add additional context in comments.

5 Comments

Why would it show the first picture when you skip the first index with slice? You also would need to get rid of the i==0 check inside.
You still get the first one because you are not referencing the array in the map
And now every item in .map function get the span with x+ photos but how do I set this to only the last one? maybe you also could help me out on that one
Check to see if it is the last one? ((item, i, arr)=> and if(arr.length-1===i)
around the span element?
3

You can also remove the first element, and retrieve it at any point, using Array.prototype.shift(); however, this modifies the original array.

const head = block.gallery.shift(); // removes and stores first element in "head"

console.log(block.gallery) // array with first element removed

1 Comment

This is the way to do it if you want to keep track of what was removed and not create a new array.

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.