I am trying to match entire arrays in Javascript. I have a userInput array and I need to find a matching array within a multi-dimensional array and output the match.
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];
I am trying to find a way to match userInput to one of the other arrays and output the matching array. With underscore.js I can find a match one at a time without looping, but that returns a bool.
var result = _.isEqual(userInput,t1) returns true
I need to find the matching array inside the configs array. I can nest loops to go through configs, but I can't figure out how to match it to userInput.
You can use Array#findIndex to find the index of the matching config in the array. Use Array#every to find the config that is equal.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With