我有一个单词数组:
["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/