user4530879
user4530879

Reputation:

converting two-dimensional array into array object in JavaScript

I have following two-dimensional array code

var questions = [
  ['How many states are in the United States?', 50],
  ['How many continents are there?', 7],
  ['How many legs does an insect have?', 6]
];

and converted version of it to array object

var questions = [
 { question: 'How many states are in the United States?', answer: 50 },
 { question: 'How many continents are there?', answer: 7 },
 { question: 'How many legs does an insect have?', answer: 6 }
]; 

and have corresponding for loops.

for (var i = 0; i < questions.length; i += 1) {
    question = questions[i][0];
    answer = questions[i][1];
    response = prompt(question);
    response = parseInt(response);
if (response === answer) {
   correctAnswers += 1;
   correct.push(question);
  } else {
   wrong.push(question);
 }
}

and

  for (var i = 0; i < questions.length; i += 1) {
      question = questions[i].question;
      answer = questions[i].answer;
      response = prompt(question);
      response = parseInt(response);
  if (response === answer) {
    correctAnswers += 1;
  } 
}

What is the actual difference between two-dimensional array and array object? Would it affect running for loop faster to sort data ? How would I know which one is better ?

Upvotes: 1

Views: 961

Answers (3)

Raos
Raos

Reputation: 394

Here is a solution in es6:

var questions = [
  ['How many states are in the United States?', 50],
  ['How many continents are there?', 7],
  ['How many legs does an insect have?', 6]
];
let keys = ["question", "answer"];
let result = questions.map(r => (keys.reduce((o, k, i) => (o[k] = r[i], o), {})));
console.log(result)

Upvotes: 2

Dylan Watt
Dylan Watt

Reputation: 3387

The difference between the two depends a lot on the environment that the Javascript is being run in. Lets just see:

http://jsperf.com/array-vs-object-lookup-986

Running that in chrome V8, you can see the difference is notable, with a edge to a map lookup. The map lookup notation is also vastly more maintainable for future devs who have to work on your code.

Edit: The map way is 5x faster FF.

Upvotes: 1

nderscore
nderscore

Reputation: 4251

Functionally, there is not much difference. Arrays are just a special type of Object. Each index in the array is just a property of that object. So, a two-dimensional array is still an array of objects.

Performance-wise, you shouldn't see any noticeable impact either way.

In regards to readability of code, the array of objects approach is much more clear about what each property's purpose is. With a two-dimensional array, there is nothing labeling what each index represents. For that reason alone, I would recommend using an array of objects in this case.

Upvotes: 0

Related Questions