3

I have a multidimensional array like this

(2) ["Vårt solsystem är 4,5 miljarder år gammalt.", "vart-solsystem-ar-45-miljarder-ar-gammalt"]
0: "Vårt solsystem är 4,5 miljarder år gammalt."
1: "vart-solsystem-ar-45-miljarder-ar-gammalt"

I what to get the value of [0] if I know [1]

I know I kan get the value of [0] if I know the index of the first array like this

var theLine = newlines[2];
console.log(theLine[0]); //Vårt solsystem är 4,5 miljarder år gammalt.

But how do I get "Vårt solsystem är 4,5 miljarder år gammalt." if I know "vart-solsystem-ar-45-miljarder-ar-gammalt".

The first dimension has about 500 records, the second dimension always has two records.

2 Answers 2

1

If I understand correctly, you want to extract a "display" value from the first nested array, where the second item of that nested matches a value you're searching for.

There are a number of ways to achieve that - for ~500 records, the following approach based on filter() and map() should be suitable:

const data = [
  ["Vårt solsystem är 4,5 miljarder år gammalt.", "vart-solsystem-ar-45-miljarder-ar-gammalt"],
  ["Foo bar", "foo-bar"],
  ["Cat video", "cat-video"]
];

function findByValue(value) {

  /* Extract first value of result to variable "result" (if any found) */
  const [result] = data
  /* Isolate sub arrays where second entry matches search value */
  .filter(item => item[1] === value) 
  /* Map first entry of filtered array sub array items */
  .map(item => item[0])

  return result;
}

console.log(findByValue("vart-solsystem-ar-45-miljarder-ar-gammalt"), "===", "Vårt solsystem är 4,5 miljarder år gammalt.");
console.log(findByValue("foo-bar"), "===", "Foo bar");
console.log(findByValue("cat-video"), "===", "Cat video");
console.log(findByValue("no-entry"), "===", undefined);

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

Comments

0

Assuming you are dealing with unique values and only looking for a single return value you can use a combination of Array#find() and Array#some() or Array#includes() or just check value equality of second element

const data = [
  [1, 2],
  [3, 4],
  [5, 6]
];

const known = 4;
console.log(data.find(arr => arr.some(val => val === known))[0])// expect 3

Comments

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.