Skip to content
Advertisement

How to get first N number of elements from an array

I am working with Javascript(ES6) /FaceBook react and trying to get the first 3 elements of an array that varies in size. I would like do the equivalent of Linq take(n).

In my Jsx file I have the following:

var items = list.map(i => {
  return (
    <myview item={i} key={i.id} />
  );
});

Then to get the first 3 items I tried

  var map = new Map(list);
    map.size = 3;
    var items = map(i => {
      return (<SpotlightLandingGlobalInboxItem item={i} key={i.id} />);
    });

This didn’t work as map doesn’t have a set function.

Can you please help?

Advertisement

Answer

I believe what you’re looking for is:

// ...inside the render() function

var size = 3;
var items = list.slice(0, size).map(i => {
    return <myview item={i} key={i.id} />
});                       
return (
  <div>
    {items}
  </div>   
)
Advertisement