Andrux51
Andrux51

Reputation: 43

Javascript - Efficient way to get distinct values from an array of objects

I'm trying to categorize an array of questions I've gotten from our application's API, and I've come up with a method that works, but it doesn't feel awesome. Can anyone tell me if there's a better way to do this?

Here's the code I have now. I'm not too worried about making it super optimized, but it shouldn't end up slow.

$scope.patron.categories = questions.map(function(question, i) {
    // check if question has a new CategoryId
    if(i === 0 || (i > 0 && question.CategoryId !== questions[i-1].CategoryId)) {
        // put questions with the same CategoryId together
        var catQuestions = questions.filter(function(q) {
            return q.CategoryId === question.CategoryId;
        });

        return {
            id: question.CategoryId,
            name: question.Category,
            collapsed: true,
            valid: false,
            questions: catQuestions
        };
    }
}).filter(function(category) {
    // because Array.prototype.map doesn't remove these by itself
    return category !== undefined;
});

Upvotes: 1

Views: 534

Answers (1)

Buzinas
Buzinas

Reputation: 11725

Although it's primarily opinion-based, I prefer a simple loop.

For sure it's better for performance, and I think it's better for readability also.

var catIds = [], cats = [];

questions.forEach(function(q, i) {
  var idx = catIds.indexOf(q.CategoryId);
  if (idx === -1) {
    catIds.push(q.CategoryId);
    cats.push({
      id: q.CategoryId,
      name: q.Category,
      collapsed: true,
      valid: false,
      questions: [q]
    });
  }
  else {
    cats[idx].questions.push(q);
  }
});

$scope.patron.categories = cats;

Upvotes: 1

Related Questions