[英]Looking for matches in multi-dimensional arrays inJavascript
我試圖在Javascript中匹配整個數組。 我有一個userInput數組,我需要在多維數組中找到匹配的數組並輸出匹配。
var t1 = [0,0,0];
var t2 = [1,0,0];
var t3 = [0,0,1];
var userInput = [0,0,0];
var configs = [t1, t2, t3];
我試圖找到一種方法將userInput匹配到其他數組之一並輸出匹配的數組。 使用underscore.js我可以一次找到一個匹配而不循環,但返回一個bool。
var result = _.isEqual(userInput,t1) returns true
我需要在configs數組中找到匹配的數組。 我可以嵌套循環來完成配置,但我無法弄清楚如何將它與userInput匹配。
您可以使用Array#findIndex
查找數組中匹配配置的索引。 使用Array#every
查找相同的配置。
var t1 = [0,0,0]; var t2 = [1,0,0]; var t3 = [0,0,1]; var userInput = [0,0,1]; // this will fit t3 (index 2) var configs = [t1, t2, t3]; var result = configs.findIndex(function(arr) { return arr.every(function(value, i) { return value === userInput[i]; }); }); console.log(result);
給定輸入,您可以使用Array.prototype.find()
, Array.prototype.toString()
或Array.prototype.join()
var t1 = [0,0,0]; var t2 = [1,0,0]; var t3 = [0,0,1]; var userInput = [0,0,0]; var configs = [t1, t2, t3]; var result = configs.find(arr => arr.join() === userInput.join()); console.log(result);
var t1 = [0,0,0]; var t2 = [1,0,0]; var t3 = [0,0,1]; var userInput = [0,0,0]; var configs = [t1, t2, t3]; var inputPresent = configs.some(a => userInput.every((u,i) => a[i] == u)); console.log(inputPresent);
如果您想知道現有輸入的索引,可以只包含一個三元組
var t1 = [0,0,0]; var t2 = [1,0,0]; var t3 = [0,0,1]; var userInput = [0,0,0]; var configs = [t1, t2, t3]; var inputIndex = -1; configs.some((a,n) => userInput.every((u,i) => a[i] == u)?(inputIndex=n,true):false); console.log(inputIndex);
這會有用嗎?
var result = _.find(configs, function(t) {
return _.isEqual(userInput, t);
});
如果您需要知道索引:
var index = -1;
_.some(configs, function(t, idx) {
if (_.isEqual(userInput, t)) {
index = idx;
return true;
}
});
// index = -1 if not found, else the first index of configs that matches the userInput
我會擔心可能存在重復的地方。 如果你可以創建一個可以可靠地測試相等性的函數,那么這只是一個過濾器。
var matches = configs.filter(config => _.isEqual(config, userInput));
var match = matches[0];
如果你想投資使用更多的庫,你可以使用像find這樣的東西
var match = _.find(configs, config => _.isEqual(config, userInput));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.