Finding matches in multidimensional arrays inJavascript
I am trying to map integer arrays in Javascript. I have a userInput array and I need to find the corresponding array in a multidimensional 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 map userInput to one of the other arrays and output the corresponding array. With underscore.js I can find a match one at a time without a loop, 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 the configs, but I can't figure out how to map them to userInput.
source to share
You can use Array#findIndex
to find the index of a suitable configuration in an array. Use Array#every
to find a configuration equal to.
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);
source to share
This input allows you to use Array.prototype.find()
, Array.prototype.toString()
orArray.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);
source to share
You can use a combination of some and every
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);
If you want to know the index of an existing input you can simply add a 3D
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);
source to share
Will this work?
var result = _.find(configs, function(t) {
return _.isEqual(userInput, t);
});
If you need to know the index:
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
source to share
I would be concerned about the place where there might be duplicates. If you can make a function that reliably checks for equality, then it's just a filter.
var matches = configs.filter(config => _.isEqual(config, userInput));
var match = matches[0];
If you want to invest more in using the library, you can use something like find
var match = _.find(configs, config => _.isEqual(config, userInput));
source to share