gpt4 book ai didi

javascript - 根据另一个数组修改一个数组

转载 作者:行者123 更新时间:2023-12-03 06:54:02 24 4
gpt4 key购买 nike

我有一个这样的短语引用数组:

const reference = ["your", "majesty", "they", "are", "ready"];
我想基于另一个数组加入上述数组的一些元素,所以如果 another这是:
const another = ["your", "they are"];
结果将是这样的:
result = ["your", "majesty", "they are", "ready"];
另一种情况要更清楚:
const reference = ["your", "majesty", "they", "are", "ready"];
const another = ["your majesty", "they are ready"];
result = ["your majesty", "they are ready"];
或者:
const reference = ["your", "majesty", "they", "are", "ready"];
const another = ["majesty they", "ready"];
result = ["your", "majesty they", "are", "ready"];
当然如果有一个空的 another我们得到与结果相同的引用:
const reference = ["your", "majesty", "they", "are", "ready"];
const another = [];
result = ["your", "majesty", "they", "are", "ready"];

最佳答案

const reference = ["your", "majesty", "they", "are", "ready"];
//const another = ["your", "they are"];
//const another = ["your majesty", "they are ready"];
//const another = ["majesty they", "ready"];
const another = [];

function formatResult(reference, another) {
//1: another is [] then return reference
if (another.length == 0) {
return reference;
} else {
//2: format the reference array with another array
another.forEach(x => {
var words = x.split(' ');
if (words.length > 1) {
var index = 0;
var sindex = 0; // if the index are countiues
for (var i = 0; i < words.length; i++) {
//find this word in refference array.
index = reference.indexOf(words[i]);
if (i == 0) {
sindex = index;
} else {
//check if the index are next to each other, if not break the loop
if (sindex != index) {
break;
}
}
sindex++;
}
if (index == sindex - 1) //to check all the index in the order
{
var startIndex = index - (words.length - 1);
//update reference array with another array.
reference.splice(startIndex, words.length, x);
}
}
})
}
return reference;
}
var result = formatResult(reference, another);
console.log(result);
Does this satisfy your question?

关于javascript - 根据另一个数组修改一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64234604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com