试着根据下面的输出要求把句子分成几个部分



当值从array2中找到时,我想打断句子,将句子推入新的数组,并将值从array2中找到的空间推入。

我希望输出云像这个

Arr=["I want to eat", "","", and, "" ]
let str = "I want to eat Banana Apple and Mango";
var array1 = str.split(" ");
var array2 = ["Banana", "Apple","Mango", "hut", "gut"];
const res = array1.map((item) =>  array2.includes(item) ? "" : item);
console.log(res);

好吧,这里的输出将像[ 'I want to eat', '', '', 'and', '' ]一样,这就是您想要的。

let str = "I want to eat Banana Apple and Mango";
var array1 = str.split(" ") 
var array2 = ["Banana", "Apple","Mango", "hut", "gut"];
const res = []
var temp = ""
array1.forEach(word => {
if(!array2.includes(word)){
temp += word + ' ';
}else{
if(temp !== "") res.push(temp)
res.push("")
temp = ""
}
})

如果您已经知道结果数组的第一个索引是什么,那么可以使用所需的值对其进行初始化。

let str = 'I want to eat Banana Apple and Mango';
let arr1 = str.split(' ');
let fruits = ["Banana", "Apple","Mango", "hut", "gut"];
let res = ['I want to eat']; // initialize it with known value
// start the loop from the values from where you are interested.
for (let i = 4; i < arr1.length; i++) {
if (fruits.includes(arr1[i])) {
res.push('');
} else {
res.push(arr1[i]);
}
}
console.log(res);

这有点不同,因为您不断地添加到上一次迭代中。forEach会处理它,reduce()也会处理它

let str = "I want to eat Banana Apple and Mango";
var array1 = str.split(" ");
var array2 = ["Banana", "Apple","Mango", "hut", "gut"];
stra = [""];
array1.forEach(e => {
if (array2.includes(e)) { stra.push(''); return; }
let i = stra.length-1 ;
stra[i] += " " + e
})
stra = stra.map(e => e.trim());
console.log(stra)
let reduce = array1.reduce((b,a) => {
if (array2.includes(a)) b.push('');
else {
let i = b.length-1 ;
b[i] += " " + a
}
return b;
},['']).map(e=>e.trim());
console.log(reduce)

试试

let str = "I want to eat Banana Apple and Mango";
const array2 = ["Banana", "Apple","Mango", "hut", "gut"];
const separator = "|";
array2.forEach(item => {
str = str.replaceAll(item, separator)
})
let result = str.split(separator).map(item => item.trim());
console.log(result);

我相信下面的代码会有所帮助:

let str = "I want to eat Banana Apple and Mango";
var array1 = str.split(" ");
var array2 = ["Banana", "Apple", "Mango", "hut", "gut"];
const res = array1.reduce((accumulator, currentVal, i) => {
const itemExist = array2.includes(currentVal);
const lastIndex = accumulator.length - 1;
if(i !== 0 && !itemExist && accumulator[lastIndex]) {
accumulator[lastIndex] = accumulator[lastIndex] + " " + currentVal;
} else {
accumulator.push(itemExist ? "" : currentVal);
}
return accumulator;
}, []);
console.log(res);

有关如何使用reduce的更多详细信息,请查看Array.reduce。

最新更新