遍历数组,添加 true 的出现次数



我一直在环顾四周,但不确定我是否在寻找正确的东西。

说我有这个

array ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't']

(我在postgresql中有一个true/false数组,我用来导入javascript,它返回为't'和'f's)

我希望将该数组更改为

[1, 3, 6, 1] (adding all the trues in between false)

假设有某种超级明显的方式我完全错过了!

Ruby:

arr.join.scan(/t+/).map(&:size)
=> [1, 3, 6, 1]

JavaScript:

arr.join('').match(/t+/gi).map(function(str) {
  return str.length
});

var arr = ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't'];
sizes = arr.join('').match(/t+/gi).map(function(str) {
    return str.length;
});
console.log(sizes);

在 JavaScript 中使用reduce()方法

var arr = ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't'];
var res = arr.reduce(function(result, e) {
  if (e == 't') { // check value is `t` and increment the last element in array
    result[result.length - 1] ++;
  } else if (result[result.length - 1] != 0) { // if element is `f` and last eleemnt is not zero then push 0 to the array
    result.push(0);
  }
  return result;
}, [0])
console.log(res);


您可以使用 ES6 箭头函数、三元运算符和逻辑短路计算来减少行数。

var arr = ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't'];
var res = arr.reduce((r, e) => {
  e == 't' ? r[r.length - 1] ++ : r[r.length - 1] == 0 || r.push(0);
  return r;
}, [0])
console.log(res);

带有Array#forEach的提案

function countT(array) {
    var r = [];
    array.forEach(function (a, i, aa) {
        a === 'f' || aa[i - 1] === 't' && ++r[r.length - 1] || r.push(1);
    });
    return r;
}
console.log(countT(['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't']));
console.log(countT(["t", "f", "t"]));
console.log(countT(["f", "f"]));
console.log(countT(["f", "t"]));
console.log(countT(["t", "f"]));
console.log(countT(["t", "t"]));

这个问题有欺骗性。尽管它明确指出"介于"之间的真值,但假值在他提供的示例中被计算在内,但事实并非如此,最后一项"t"被计算在内,即使它后面没有"f"。所以我在这里有两个解决方案。这个满足了这个例子。

var a = ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't'],
 code = a.reduce((p,c) => (c == "t" ? p[p.length-1]++ : !!p[p.length-1] && p.push(0),p), [0]);
console.log(code);

而这个满足了问题的字面描述。

var a = ['t', 'f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't'],
    r = [],
    n = 0;
    a.reduce((p,c) => (p != c ? c == "t" ? n++
                                         : n && (r.push(n),n=0)
                              : c == "t" && n++
                      ,c));
console.log(r);

最新更新