最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mapping array into array of tuples using LoDash - Stack Overflow

programmeradmin0浏览0评论

I've got an array such as:

var foo = [1, 2, 3, 4, 5];

and I would like to map it to:

var bar = [[1,2], [2,3], [3,4], [4,5], [5,1]];

I do not need to handle scenarios where the length of foo is 0 or 1.

My naive approach is:

var foo = [1, 2, 3, 4, 5];
var bar = _.map(foo, function(value, index) {
  return index < foo.length - 1 ? [value, foo[index + 1]] : [value, foo[0]];
});

console.log(bar);
<script src=".10.1/lodash.js"></script>

I've got an array such as:

var foo = [1, 2, 3, 4, 5];

and I would like to map it to:

var bar = [[1,2], [2,3], [3,4], [4,5], [5,1]];

I do not need to handle scenarios where the length of foo is 0 or 1.

My naive approach is:

var foo = [1, 2, 3, 4, 5];
var bar = _.map(foo, function(value, index) {
  return index < foo.length - 1 ? [value, foo[index + 1]] : [value, foo[0]];
});

console.log(bar);
<script src="https://cdn.jsdelivr/lodash/3.10.1/lodash.js"></script>

I'm wondering if there's a more clear way to express this mapping.

Share Improve this question edited Dec 7, 2016 at 0:17 Dekel 62.7k12 gold badges108 silver badges130 bronze badges asked Dec 7, 2016 at 0:10 Sean AndersonSean Anderson 29.4k33 gold badges132 silver badges242 bronze badges 6
  • This question is more suited for code review. You already solved the problem but you are seeking directions to improve. – Emile Bergeron Commented Dec 7, 2016 at 0:49
  • @EmileBergeron Please note that Code Review requires real code; questions containing placeholders like foo would be off-topic there. – 200_success Commented Dec 7, 2016 at 1:22
  • 1 @200_success Yes you're right, I'm personally not a user of Code Review, so my experience is limited with it, but OP could take the real function he's using and it would work. It would even be better since maybe there's a better solution for his scenario than grouping the array. – Emile Bergeron Commented Dec 7, 2016 at 1:26
  • 2 @EmileBergeron there are currently 685 unanswered 'javascript' questions on CR - surely one of them is waiting for your review! ;-) – Mathieu Guindon Commented Dec 7, 2016 at 1:32
  • 1 @Mat'sMug I actually read the rules this week and was thinking in doing some reviews. – Emile Bergeron Commented Dec 7, 2016 at 1:40
 |  Show 1 more ment

2 Answers 2

Reset to default 7

Using plain simple lodash. First drop the first element from the array, append it, and then zip it with the original array:

var a = [1,2,3,4,5]
var b = _.zip(a, _.concat(_.drop(a), a[0]))

The result:

console.log(b)
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 1]]

_.nth

Gets the element at index n of array. If n is negative, the nth element from the end is returned.

just get sibling in reverse order

var bar = _.map(foo, function(val, index) {
    return [val, _.nth(foo, (index + 1) - foo.length)];
});
发布评论

评论列表(0)

  1. 暂无评论