如何检查添加到数组的数据是否已存在于不同的数组中?

时间:2017-08-23 22:16:10

标签: javascript arrays google-sheets

我希望为Google工作表创建一个简单的脚本,其中数组1已经填充了一个名称列表。当新名称添加到数组2时,将检查数组1的名称。如果在阵列1中存在输入到阵列2中的名称,则将执行动作。每次向阵列2添加新名称时都必须执行此搜索功能,以确定它是否存在于阵列1中。

function findPlayer() {
var ss = SpreadsheetApp.getActiveSpreadsheet()

var picksRange = ss.getRange("B2:M15");
var poolRange = ss.getRange("B21:G96");

var picksPlayerName = picksRange.getValues(); 
var poolPlayerName = poolRange.getValues(); 

for (var i = 0; i < picksRange.length; i++)
for (var j = 0; j < poolRange.lenth; j++)

if (picksPlayerName[i] == poolPlayerName[j]) {
 poolPlayerName[i].setBackground("red")}
else {
 poolPlayerName[j].setBackground("blue");}
}

1 个答案:

答案 0 :(得分:0)

这不是一个完整的答案,也不完全适合您的用例,但您应该可以从这里获取它,或者当您对代码的特定部分有疑问时可能会再回答其他问题

const existingNames = ["Carl", "Emma", "Sarah", "Ahmad"];
const newNames = ["Emma", "Sarah", "Isa", "Igor", "Kent"];

// go through the new names and check against existing ones  
newNames.forEach(newName => {
    if(existingNames.includes(newName)) {
    // handle duplicates: do nothing? 
   } else {
    // handle new names: maybe add them to the existing names?
    existingNames.push(newName);
   }
});

console.log('After going through all new names, the complete list of known names are: ' + existingNames);

演示您可以在其中使用代码并了解:https://jsfiddle.net/jonahe/11uom4cu/