Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have one array like this one:

array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}]

I have a second array of integer :

array2=[1,3]

I would like to obtain this array without a loop for :

arrayResult = ['value1', 'value3']

Does someone know how to do it with javascript ?

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

Map the elements in array2 to the label property of the element in array1 with the corresponding value:

array2                      // Take array2 and
  .map(                     // map
    function(n) {           // each element n in it to
      return array1         // the result of taking array1
        .find(              // and finding
          function(e) {     // elements
            return          // for which 
              e.value       // the value property
              ===           // is the same as 
              n;            // the element from array2
          }
        )
        .label              // and taking the label property of that elt
      ;
    }
  )
;

Without comments, and in ES6:

array.map(n => array1.find(e => e.value === n).label);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...