Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for matches in multi-dimensional arrays inJavascript

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.

like image 275
jk42 Avatar asked Jan 30 '26 14:01

jk42


1 Answers

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);
like image 88
Ori Drori Avatar answered Feb 02 '26 06:02

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!