0

I have a 2 dimensional array

var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];

And I want to get the number of years based on user Input, which is -1,1,2,3 how can I do it in Javascript?

I'm trying using years[years_input] but I don't get the correct value.

5 Answers 5

1

You can use the find() method.

var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];

let input = +prompt('enter the index');
console.log(years.find(x => x[0] === input)[1])

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

2 Comments

Thanks, but that's not what I'm trying to get. Basically I need to get "0 years" "< 1 year" based on the input which is -1 or 1 or 2 or 3
Perfect, works like a charm, I'll accept your answer in 8 min, thanks :)
1

You can use includes:

var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];

var input = +prompt()

for(var i = 0; i < years.length; i++) {
  if (years[i].includes(input)) {
  console.log(years[i][1])
  break
  }
}

Comments

1

Get the first element of the array (you need to use find for edge cases like -1):

const years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];
const index = 3;
const [, res] = years.find(([n]) => n == index);
console.log(res);

7 Comments

Thanks, but that's not what I'm trying to get. Basically I need to get "0 years" "< 1 year" based on the input which is -1 or 1 or 2 or 3
No problem @Radu033, always glad to help.
@JackBashford This won't work when the input is -1.
Fixed @Kobe, any better?
@Shubh because we want the second item - it's a 2d Array
|
1

Try this,hope it works

let years = [
  [-1, "0 years"],
  [1, "< 1 year"],
  [2, "1-3 years"],
  [3, "> 3 years"]
];

function getYear(year) {

  return years.find(el => el.indexOf(year) > -1)[1]

}

console.log(getYear(-1))
console.log(getYear(1))
console.log(getYear(2))
console.log(getYear(3))

Comments

0

You could take a Map with Map#get and the key for getting the value.

var years = [[-1, "0 years"], [1, "< 1 year"], [2, "1-3 years"], [3, "> 3 years"]],
    yearsMap = new Map(years);

console.log(yearsMap.get(1));

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.