JavaScript:如何处理所有后续的元素对?

标签 javascript lambda functional-programming reduce

我有一个单词数组:

["get", "out", "of", "the", "way"]

和一个函数:

isPrepOrParticle

对于 “out”“of” 元素返回 true

我想用下划线将所有 true 元素粘附到之前的元素上并得到以下内容:

["get_out_of", "the", "way"]

是否有一个很好的函数式方法通过对所有后续元组应用某种函数来做到这一点:

f = (a, b) => {
  if (isPrepOrParticle(b)) return a + "_" + b;

  return null;
}

最佳答案

因为您需要操作数组和单个元素,所以我认为 Array.reduce 是您最好的选择。

var words = ["get", "out", "of", "the", "way"];
var special = ["out", "of"];

var janked = words.reduce((acc, el) => {
  if (special.includes(el) && acc.length) {
    // append underscore + current element to previous element
    acc[acc.length - 1] += "_" + el;
  } else {
    // just add this element to the array
    acc.push(el);
  }
  return acc;
}, []);

console.log(janked);

关于JavaScript:如何处理所有后续的元素对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127638/

相关文章:

c# - 在 Expression<Func<TModel, Object>> 中评估参数结果

c# - 是否有具有持久不可变 Vector 类的 .net 库(如 Clojure/Scala 中所见)?

javascript - 如何测试另一个函数内的函数调用? Jest

javascript - 在 JavaScript 中,用于解析特定字符串的正确 `Temporal` 类型是什么?

javascript - jQuery 按输入名称选择

functional-programming - ML类型功能,小窍门?

c++ - c++ 模板元编程是函数式编程的一种形式吗

javascript - 将对象键值对转换为Javascript中的一系列数组

python - 复选框以取消选中所有其他复选框

c# - 是否可以将lambda表达式存储在数组C#中