javascript - How would one go about implementing `zipWithIndex` in underscore.js? -


essentially when zipwithindex applied on array should produce array key value , value array element (or vice versa).

update

based on op's comments, return value should array of objects, each of contains single property inverted property (i.e. keys & values swap places) of input array/object.

function invert(list) {   return _.map(list, function(val, key) {     var obj = {};     obj[val] = key;     return obj;   }); } 

example 1: ['a', 'b', 'c'] ==> [{a:0}, {b:1}, {c:2}]

example 2: {key1:'a', key2:'b'} ==> [{a:'key1'}, {b:'key2'}]

function invert(list) {    return _.map(list, function(val, key) {      var obj = {};      obj[val] = key;      return obj;    });  }      function doalert(input) {    alert (json.stringify(input) + ' ==> ' + json.stringify(invert(input)));  }    doalert(['a', 'b', 'c']);  doalert({key1: 'a', key2: 'b'});
<script src="http://underscorejs.org/underscore-min.js"></script>

like _.invert function in underscore.js, values must serializable (i.e. convertable strings) have predictable behavior.


original answer

consider:

function zipwithindex(list) {   return _.map(list, function(val, key) { return [val, key]; }); } 

this should work both objects & arrays (anything can iterated, far _.map concerned).

this implementation of zipwithindex based on scala's implementation (the used language find function defined).

function zipwithindex(list) {    return _.map(list, function(val, key) { return [val, key]; });  }      function doalert(input) {    alert (json.stringify(input) + ' ==> ' + json.stringify(zipwithindex(input)));  }    doalert(['a', 'b', 'c']);  doalert({key1: 'a', key2: 'b'});
<script src="http://underscorejs.org/underscore-min.js"></script>


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -