Setting range Underscore.js ()

Using range() in Underline, I can do something like this:

 _.range(10); >> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

Can I somehow modify / use this to create a result like this:

 solution(); >> {0: true, 1: true, 2: true, 3: true} 

The solution may also include jQuery.

+4
source share
2 answers

Yes.

 var range = _.range(10); _.map(range, function() { return true; }); 

jsFiddle .

If you must have an object (the first returns an array), run it as a result ...

 _.extend({}, range); 

jsFiddle .

It is worth mentioning that if you did not have Underscore or if you wanted to use jQuery, there are equivalents to $.map() and $.extend() .

+8
source

The accepted answer is only suitable for this question, but it should be noted that, as indicated, it will only work for a number of incremental integers starting from zero, since it actually uses the index, not the value of the element.

Here is another one of many possible solutions. When I need to turn an array into a hash search, I do this:

 var range = _.range(10); var hash = _.object(range, range.map(_.const(true))); 

This will take into account the actual values ​​in your source array, which can be numbers or strings in any order.

I do not particularly recommend this, but if you can be sure that your original range does not contain zero, you can simplify it further, since all values ​​will be true:

 var hash = _.object(range, range); 
0
source

Source: https://habr.com/ru/post/1439365/


All Articles