Himmators
Himmators

Reputation: 15006

How to return an array from a map?

I want to return 0, 1 or 2 images from a javascript-map, depending on how many there are.

  function images () {
    if (item.has('images')) {
      const response = [item.get('images').get(0)]
      if(item.get('images').has(100)){
        response.push(item.get('images').get(1))
      }
      return response
    } else {
      return []
    }
  }

This is how I currently do it. If I had an array of images, I could simply do

return arr.slice(0,2)

Could I do something similar with a map?

Upvotes: 0

Views: 76

Answers (1)

ssube
ssube

Reputation: 48247

Yes! Maps are iterable and you can destructure iterables with ease:

const m = new Map([['a', 1], ['b', 2], ['c', 3]]);
const [head, next] = m.values();
console.log(head, next);

Specifically, I think the Map.prototype.values method will help you. It returns an iterable (although not necessarily an array) of values from the map.

Combine that with a little bit of logic:

function images (m) {
  if (m.has('images')) {
    const data = m.get('images'), values = data.values();
    if (data.size < 100) {
      const [head] = values;
      return [head];
    } else { 
      const [head, next] = values;
      return [head, next];
    }
  } else {
    return [];
  }
}

You may be able to clean up the repeated [foo, bar] = baz pattern, although I'm not sure the best way. Felix Kling's comment with Array.from and slice will certainly work, although it may be slow with large maps.

Upvotes: 1

Related Questions