对于两个长度不同的数组中的记录匹配,我几乎不需要帮助。
要求:
示例:
var findFrom = ["Apple", "Mango", "Orange", "Mango", "Mango", "Apple"];
var findTheseValues = ["Apple", "Mango"];
Returned Array = ["Apple", "Apple("Matched")", "Orange", "Mango", "Mango("Matched")", "Mango", "Mango(Matched)", "Apple("Matched")"];
**// Push matched values next to the value that was matched in the FindFrom Array**
我尝试过:
var findFrom = ["Apple", "Mango", "Orange", "Banana", "Orange", "Orange","Orange"];
var findTheseValues = ["Orange", "Banana"];
for(let i = 0; i < findFrom.length; i++){
if (findFrom[i] === findTheseValues[i] // toString() if required){
console.log(findFrom[i]);
}
}
如果我只是将if条件中的'i'替换为0,则会返回匹配的值,但我不希望它仅匹配一个值-它应该遍历两个数组。
尝试从ES 6查找,但是它只返回一个匹配的值。
如果需要,我很乐意解释更多,感谢您的帮助! :)
答案 0 :(得分:1)
您可以使用.map()
和.includes()
方法:
let findFrom = ["Apple", "Mango", "Orange", "Mango", "Mango", "Apple"],
findTheseValues = ["Apple", "Mango"];
let result = findFrom.map(s => s + (findTheseValues.includes(s) ? ` (${s})` : ''));
console.log(result);
文档:
答案 1 :(得分:0)
您可以使用Arrays映射方法,该方法将返回一组新数组,并附加匹配的文本。
var returnedArray = findFrom.map((ele)=> {
if(findTheseValues.indexOf(ele)!==-1){
return [ele, ele+"(matcheed)"] // return a pair with appended matched
}else{
return ele;
}
}).join().split(',') // to flatten array.
答案 2 :(得分:0)
此解决方案对我有用:
var findFrom = ["Apple", "Mango", "Orange", "Mango", "Mango", "Apple"];
var findTheseValues = ["Apple", "Mango"];
var solution = [];
for(let i = 0; i < findFrom.length; i++){
solution.push(findFrom[i]);
if (findTheseValues.indexOf(findFrom[i]) !== -1) {
solution.push(findFrom[i] + ' (Matched)');
}
}
console.log(solution)
这会遍历数组,尝试在“ findthesevalues”的索引处找到元素-然后,如果找到匹配项,则将“ matched”字符串推到新数组中
答案 3 :(得分:0)
这是一个使用本机Array方法而非for循环的不错的解决方案,恕我直言,这总是一个更好的主意。
此外,这还将 允许您多次查找相同的值,例如在搜索中多次包含一个值。
let findFrom = ["Apple", "Mango", "Orange", "Mango", "Mango", "Apple"];
// try either of the following
let findTheseValues = ["Apple", "Mango"];
//let findTheseValues = ["Apple", "Mango", "Mango"];
let results = [];
findFrom.forEach((i) => {
const match = findTheseValues.filter((a) => i === a);
const result = match.length > 0 ? match.concat(i) : i;
results.push(i);
if (match.length > 0) {
match.forEach(m => results.push(m));
};
});
console.log(results);
答案 4 :(得分:0)
我会做这样的事情
var findFrom = ["Apple", "Mango", "Orange", "Mango", "Mango", "Apple"];
var findTheseValues = ["Apple", "Mango"];
var matches = findFrom.map((e, i)=>{
return r = findTheseValues.includes(e) ? e + '(matched)' : e;
});
console.log(matches);
答案 5 :(得分:0)
我之所以写这个答案,是因为提出的所有其他解决方案均基于对findTheseValues
数组的线性搜索,而使用不同的数据结构可以绝对降低总的计算复杂度:我在谈论Set
或Map
个。它们可能是使用哈希表实现的,正如ECMAScript标准所说:
必须使用哈希表或其他机制来实现,这些机制通常提供的访问时间与集合中元素的数量成线性关系。
因此,除了使用的数据结构外,我的解决方案几乎与其他解决方案相同。
let findTheseValuesSet = new Set(findTheseValues);
let newArray = [];
findFrom.forEach(elem => {
newArray.push(elem);
if (findTheseValuesSet.has(elem))
newArray.push(elem + '(Matched)');
});