2

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"?

4
  • 2
    Welcome to stackoverflow. What have you tried? This is not a code writing service, and we expect people to show they have put effort into trying to solve the problem themselves. Please have a read of the help center and the How to Ask section in particular Commented Jul 9, 2019 at 13:45
  • Can you expand your reply? I'm not very familiar with JavaScript and don't quite understand. Commented Jul 9, 2019 at 13:45
  • @messerbill then you should know map is a bad recommendation for this problem ... Commented Jul 9, 2019 at 13:48
  • @messerbill map performs an operation on every element of the input array and produces a new output array. that has nothing to do with the question being asked - we don't want to perform an operation on every element and we don't want to create a new array. Commented Jul 9, 2019 at 13:53

3 Answers 3

4

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);

Sign up to request clarification or add additional context in comments.

17 Comments

in your first example, use array.find(...) || [] that way [,res] = ... will never throw an error. If no match is found, res will be undefined
OK @user633183, I'll edit my answer to improve stability.
Fixed @user633183, better now? (I don't need to add to filter because it's [] by default).
@JackBashford ... || [, "Default Value"] works but it's rather ugly. If you wanted to add default value functionality, I would sooner do: const r = array.find(...); return r === undefined ? "default value" : r[1]; it's not as pretty, but it's more clear, imo. My original suggestion to add ... || [] gives res = undefined which matches the behavior of find and is probably good enough.
Thank you so much for the positive feedback @user633183 - as one of the more experienced users on the site, both in JavaScript and more generally, I take that at very high face value.
|
1

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

Comments

0

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'])

7 Comments

the major downside to this answer is the entire input needs to be transformed before the answer can be returned - this is wasteful compared to approaches which stop reading the input as soon as the match is encountered.
@user633183, one approach is to convert it to object one time for making easy for further searches , instead of looping for every search
Correct, if many lookups are required, a data type offering better search capabilities would offer a much better performance. Consider Map in this case.
@user633183, updated option 2 to create object from that array and using it for every other following searches
Your second solution reduce suffers from the same problem. It will traverse the entire input array even though a result could be returned sooner. Using reduce like this is effectively writing Object.fromEntries by hand.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.