Prerona Kundu
Prerona Kundu

Reputation: 113

Search through multidimensional Javascript array

I have an array set up like the following:

var array = [["A1", "left:81px"], ["A2", "left:145px"],...]

The purpose of this is to take a user input and search through this array to find the location to move an element to. If the user input is "A1" how can I parse through this array to set some variable equal to "left:81px"?

Upvotes: 2

Views: 85

Answers (3)

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result, use Object.fromEntries to convert key ,value pair array to object - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

  1. Convert key-value pairs array to object using Object.fromEntries.
  2. Find value using key value like A1,A2

working code sample

var arr = [["A1", "left:81px"], ["A2", "left:145px"]]
function findVal(word, arr){
  var obj = Object.fromEntries(arr)
  return obj[word]
  
}
console.log(findVal('A1', arr))

Option 2: Using reduce and converting key ,value pair array to object one time and use for further searches everytime and also for better browser compatibility compare to Object.fromEntries

var arr = [["A1", "left:81px"], ["A2", "left:145px"]]
var obj = arr.reduce((acc,v)=>{
    acc[v[0]] = v[1]
    return acc
  }, {})
console.log(obj['A1'])

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44145

Use find and some simple destructuring.

var array = [
  ["A1", "left:81px"],
  ["A2", "left:145px"]
];

const [, res] = array.find(([k]) => k == "A1") || [];

console.log(res);

The above returns undefined if no value is found.

Slightly simpler code:

var array = [
  ["A1", "left:81px"],
  ["A2", "left:145px"]
];

const input = "A1";
let res = "";

for (let i = 0; i < array.length; i++) {
  if (array[i][0] == input) {
    res = array[i][1];
    break;
  }
}

console.log(res);

Upvotes: 4

Phillip
Phillip

Reputation: 6253

Assuming that the inner arrays are always structured like [key, value]:

// this is your array.
const array = [["A1", "left:81px"], ["A2", "left:145px"]]

// user input:
const query = "A1";

// find an inner array in array whose first element matches the user input
const [, result] = array.find(([key]) => key === query) || []

console.log(result);

If possible, you should use a better (map-like) data structure for this:

const data = {
  A1: 'left:81px',
  A2: 'left:145px'
};

const query = 'A1';

const result = data[query];
console.log(result);

The array version has a linear runtime where as the second one is constant time. If you will do this lookup often, it is worth converting your array representation to an object

Upvotes: 1

Related Questions