合并一些数组项

时间:2016-02-01 19:08:42

标签: javascript arrays functional-programming

我是函数式编程的新手,我尝试执行以下操作:假设我有一系列值:['a','b-','c']并且我希望每个以a结尾的项目'-'与以下数组条目合并:['a','b-c']

当然,我可以通过制作for循环来实现这一目的:

var test = ['a', 'b-', 'c'], result = [];

for (var i=0;i<test.length;i++) {
  var curr = test[i];
  if (curr.endsWith('-')) {
    curr += test[i+1];
    i++;
  }
  result.push(curr);
}

但如果没有for循环,怎么能这样做呢?

6 个答案:

答案 0 :(得分:5)

老实说,你编程的方式可能是最有效的方法。

但是,这是另一种选择:

&#13;
&#13;
var test = ['a', 'b-', 'c'],
    result = test.join().replace(/-,/g, '').split(',');

console.log(result);
&#13;
&#13;
&#13;

这会将所有元素连接成一个字符串:'a,b-,c',删除所有出现的'-,'&gt; 'a,bc',然后将字符串拆分为具有所需结果的数组,如输出中所示。

通过更改join / split中使用的分隔符,可以稍微进行一些防范:

var test = ['a', 'b-', 'c'],
    separator = '||',
    result = test.join(separator)
        .replace(new RegExp('-' + separator, 'g'), '')
        .split(separator);

答案 1 :(得分:2)

一种可能的方法(使用key_A_pressed = False running = True while running: # check events for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == pygame.K_q: running = False elif event.key == pygame.K_a: key_A_pressed = True # it is executed only once print "Key A - start pressing" if event.type == KEYUP: if event.key == pygame.K_a: key_A_pressed = False # it is executed only once print "Key A - stop pressing" # do it only once - outside of `for event` loop # it is executed many times #if pygame.key.get_pressed()[pygame.K_a]: # or if key_A_pressed: print "Key A is held pressed..." pygame.display.update() ):

.reduce

答案 2 :(得分:1)

这也可以使用Array.prototype.map

来实现
var test = ['a', 'b-', 'c'];

var result = test.slice().map(function (x, i, a) {
    if (x.endsWith("-") && a[i+1]) {
        var r = x + a[i+1]; // Join this and the next element in the array
        a.splice(i, 1); // Remove the next element from the array
        return r;
    }
    return x;
}).filter(function (x) {
    return typeof x !== 'undefined';
}); // Since the array comes back with a different length and some undefined elements, remove those. Thanks @Cerbrus for pointing this out

console.log(test, result, result.length); // ["a", "b-", "c"] ["a", "b-c"] 2

答案 3 :(得分:0)

这种方式适用于连续的多个虚线元素,如果最后一个元素有短划线,则使用Array.forEach

var test = ['a', 'b-', 'c-'], result = [], next = "";

test.forEach(function(curr) {
  if (curr.endsWith('-')) {
    next += curr;
    if (curr == test[test.length-1]) {
      result.push(next);
    }
 }else {
   result.push(next + curr);
   next = "";
 }
});
document.write(result);

答案 4 :(得分:0)

另一个map + filter。最有可能更慢,因为过滤器在数组中添加了另一次迭代,但是与原始数据一样(当有多个 - 时,这可能不是OP想要的那样)一排)。

&#13;
&#13;
var test = ['a', 'b-', 'c-', 'd', 'e'], result = [];

result = test
	.map((curr, i, array) => (curr.endsWith('-') && array[i + 1] !== undefined) ? curr + array[i+1] : curr)
	.filter((curr, i, arr) => (i>0 && arr[i-1].length > 1 && curr.length === 1) ? false : true)

document.write(result);
&#13;
&#13;
&#13;

答案 5 :(得分:0)

没有读完所有的答案,所以如果我再说一遍,那么。已经说过了。

函数式编程并不意味着总有一个预定义函数可以完全按照您的意图执行;或某些的组合。
有时候写一个简单的短效用函数比滥用那些已经存在的函数更好。

一些“问题”怎么样,比如彼此相邻的多个虚线值,或者在列表的末尾?你想怎么处理这些案件?
这将是我的实施:

function combineDashedStrings(arr){
    var result = [], pending = ""
    for (var i=0; i<arr.length; i++) {
        var curr = pending + arr[i];

        pending = curr.endsWith("-") && curr || "";                 //multiple concats
        //pending = !pending && curr.endsWith("-") && curr || "";   //single concat

        pending || result.push(curr);
    }
    //pending && result.push(curr); //add last item if it contains a dash
    return result
}

combineDashedStrings(['a', 'b-', 'c-', 'd', 'e-']);

随意切换注释行/选项