3

Is there Ruby's map-like syntax in JavaScript? for example in Ruby I could write:

res = [[1,2,3],[4,5,6],[7,8,9]]
res = res.map { |x| x[1..2] } 
# res == [[2, 3], [5, 6], [8, 9]]

Is there any function that works like that in JavaScript?

asked Mar 26, 2015 at 11:37
2

2 Answers 2

3

You could check out Underscore.js Map helper function (there is also MapObject helper, similar to map, but works with objects): http://underscorejs.org/#map

_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
_.map([[1, 2], [3, 4]], _.first);
=> [1, 3]

Failing that, you could try ES6 map object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var kvArray = [["key1", "value1"], ["key2", "value2"]];
// Use the regular Map constructor to transform a 2D key-value Array into a map
var myMap = new Map(kvArray);
myMap.get("key1"); // returns "value1"
// Use the spread operator to transform a map into a 2D key-value Array.
alert(uneval([...myMap])); // Will show you exactly the same Array as kvArray
// Or use the spread operator on the keys or values iterator to get 
// an array of only the keys or values
alert(uneval([...myMap.keys()])); // Will show ["key1", "key2"]

If you decide on ES6, you will also need a transpiler such as Babel.

Hope that helps.

answered Mar 26, 2015 at 11:58
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome to Stack Overflow! Please quote the most relevant part of the link, in case the target site is unreachable or goes permanently offline. See How do I write a good answer.
2

you can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

For browsers that don't support the Array map method, here's an alternative implementation:

if (!Array.prototype.map) {
 Array.prototype.map = function(fun /*, thisp*/) {
 var len = this.length >>> 0;
 if (typeof fun != "function") {
 throw new TypeError();
 }
 var res = new Array(len);
 var thisp = arguments[1];
 for (var i = 0; i < len; i++) {
 if (i in this) {
 res[i] = fun.call(thisp, this[i], i, this);
 }
 }
 return res;
 };
}

or

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill

answered Mar 26, 2015 at 11:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.