Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Hash from an Array using the Prototype JavaScript framewor?

I've an Array ['red', 'green', 'blue']

I want to create a new Hash from this Array, the result should be

{'red':true, 'green':true, 'blue':true}

What is the best way to achieve that goal using Prototype?

like image 605
denisjacquemin Avatar asked Sep 26 '10 13:09

denisjacquemin


2 Answers

Just iterate over the array and then create the Hash:

var obj  = {};
for(var i = 0, l = colors.length; i < l; i++) {
    obj[colors[i]] = true;
}
var hash = new Hash(obj);

You can also create a new Hash object from the beginning:

var hash = new Hash();
for(var i = 0, l = colors.length; i < l; i++) {
    hash.set(colors[i], true);
}

I suggest to have a look at the documentation.

like image 75
Felix Kling Avatar answered Nov 14 '22 20:11

Felix Kling


This functional javascript solution uses Array.prototype.reduce():

['red', 'green', 'blue']
.reduce((hash, elem) => { hash[elem] = true; return hash }, {})

Parameter Details:

  • callback − Function to execute on each value in the array.
  • initialValue − Object to use as the first argument to the first call of the callback.

The third argument to the callback is the index of the current element being processed in the array. So if you wanted to create a lookup table of elements to their index:

['red', 'green', 'blue'].reduce(
  (hash, elem, index) => {
    hash[elem] = index++;
    return hash
  }, {});

Returns:

Object {red: 0, green: 1, blue: 2}
like image 36
Mike Fabrikant Avatar answered Nov 14 '22 21:11

Mike Fabrikant