9

I have got a javascript array, and I want to extract the first 10 items from it. Is this possible to use map method for this?

the code I tried is below:

data.map((item, i) => {
  placeIDs.push(item.place_id);
});

This code block returns 20 place_ids but I want to have only 10.

So I tried break inside the map method, and it says SyntaxError: Illegal break statement.

Here data is json result from google place api, and it returns 20 results.

One result

{
    "geometry": {
      "location": {
        "lat": 61.2180556,
        "lng": -149.9002778
      },
      "viewport": {
        "northeast": {
          "lat": 61.48393789999999,
          "lng": -148.4600069
        },
        "southwest": {
          "lat": 60.733791,
          "lng": -150.4206149
        }
      }
    },
    "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
    "id": "2edc2d446c844a7a55a2ccbe4a2dfda60a5a0264",
    "name": "Anchorage",
    "photos": [
      {
        "height": 1152,
        "html_attributions": [
          "<a href=\"https://maps.google.com/maps/contrib/102061280252416580615\">Efren Norstein</a>"
        ],
        "photo_reference": "CmRaAAAA9aiV4_BwvK6GfpuswWMBzwuO4LM55YUxGuN8q-4kyZ2-eeyl386ArGmc0-qyBr1r49cuibTIx_2QjFNIBoSRZFspgTBKzciji_-srPClBjNKx8q02BmvwM5vZxVy71lSEhDSY8VwSU2I6uHJPBVvZStBGhQ-_-ZcvP8QhktxugB9k_YHr3OX6A",
        "width": 2048
      }
    ],
    "place_id": "ChIJQT-zBHaRyFYR42iEp1q6fSU",
    "reference": "ChIJQT-zBHaRyFYR42iEp1q6fSU",
    "scope": "GOOGLE",
    "types": ["locality", "political"],
    "vicinity": "Anchorage"
  },

placeIDs is an array. I want to extract place_ids from the first 10.

So the main idea is that is it possible to break the map inside it?

Kid
  • 1,160
  • 2
  • 14
  • 31

3 Answers3

19

This will do the job. Replace [startIndex] and [endIndex] with 0 and 10 to get the first 10.

data.slice([startIndex], [endIndex]).map((item, i) => {
  placeIDs.push(item.place_id);
});
Thor Jacobsen
  • 8,621
  • 2
  • 27
  • 26
9

Take a look at slice https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

E.g. const my10Items = myArray.slice(0, 10);

Mick
  • 837
  • 8
  • 23
1
var mapdata = [{ a: "x", b: "y" }, { a: 1, b: 2 }, { a: "m", b: "n" }, { a: "aa", b: "bb" }, { a: "11", b: "22" }];
var result = mapdata.splice(0, 3).map(_data => {
                return { a: _data.a };
})
// result is [{"a":"x"},{"a":1},{"a":"m"}]
   or
   var result = mapdata.splice(0, 3).map(_data => {
              return _data.a;
   })
// result is ["x", 1, "m"]
RamPrakash
  • 1,687
  • 3
  • 20
  • 25