1

I have an object which contains questions and each question has a different difficulty denoted by allQuiz[x].difficulty.

I have written a for loop which will sort the questions in their relative difficulty categories. For example difficulty 25 = easy , difficulty 50 = medium etc.

Here's a portion of the object structure:

 {
    "id": "41",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "50",
    "question": {
       "Voice": "Which fictional city is the home of Batman?",
       "Display": "Which fictional city is the home of Batman?"
    },
    "answer": {
       "Voice": "Gotham City",
       "Display": "Gotham City"
    }
 },
 {
    "id": "42",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "50",
    "question": {
       "Voice": "The Hunchback of Notre Dame was also known as?",
       "Display": "The Hunchback of Notre Dame was also known as?"
    },
    "answer": {
       "Voice": "Quasimodo",
       "Display": "Quasimodo"
    }
 },
 {
    "id": "43",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "75",
    "question": {
       "Voice": "The title role of the 1990 movie Pretty Woman was played by which actress?",
       "Display": "The title role of the 1990 movie Pretty Woman was played by which actress?"
    },
    "answer": {
       "Voice": "Julia Roberts",
       "Display": "Julia Roberts"
    }
 },
 {
    "id": "44",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "75",
    "question": {
       "Voice": "Which Tom Hanks movie won the Academy Award for Best Picture in 1994?",
       "Display": "Which Tom Hanks movie won the Academy Award for Best Picture in 1994?"
    },
    "answer": {
       "Voice": "Forrest Gump",
       "Display": "Forrest Gump"
    }
 },
 {
    "id": "45",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "100",
    "question": {
       "Voice": "Jonny Depp starred as Jack Sparrow in which series of movies?",
       "Display": "Jonny Depp starred as Jack Sparrow in which series of movies?"
    },
    "answer": {
       "Voice": "Pirates of the Caribbean",
       "Display": "Pirates of the Caribbean"
    }
 },
 {
    "id": "46",
    "category": "TV & Movies",
    "locales": "GB#US",
    "difficulty": "100",
    "question": {
       "Voice": "Marion Crane is the tragic figure in which cult horror film?",
       "Display": "Marion Crane is the tragic figure in which cult horror film?"
    },
    "answer": {
       "Voice": "Psycho",
       "Display": "Psycho"
    }
 },


    {
        "id": "47",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "25",
        "question": {
           "Voice": "Alexander Graham Bell invented which communication tool?",
           "Display": "Alexander Graham Bell invented which communication tool?"
        },
        "answer": {
           "Voice": "Telephone",
           "Display": "Telephone"
        }
     },
 {
        "id": "48",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "75",
        "question": {
           "Voice": "Steve jobs was the founder of which tech giant?",
           "Display": "Steve jobs was the founder of which tech giant?"
        },
        "answer": {
           "Voice": "Apple",
           "Display": "Apple"
        }
     },
     {
        "id": "49",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "75",
        "question": {
           "Voice": "Which year was Amazon founded?",
           "Display": "Which year was Amazon founded?"
        },
        "answer": {
           "Voice": "1994",
           "Display": "1994"
        }
     },
     {
        "id": "50",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "100",
        "question": {
           "Voice": "What is the natural habitat of an arboreal creature?",
           "Display": "What is the natural habitat of an arboreal creature?"
        },
        "answer": {
           "Voice": "Trees",
           "Display": "Trees"
        }
     },
     {
        "id": "51",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "25",
        "question": {
           "Voice": "What is a geiger counter used to detect?",
           "Display": "What is a geiger counter used to detect?"
        },
        "answer": {
           "Voice": "Radiation",
           "Display": "Radiation"
        }
     },
     {
        "id": "52",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "50",
        "question": {
           "Voice": "What element on the periodic table has the chemical symbol H?",
           "Display": "What element on the periodic table has the chemical symbol H?"
        },
        "answer": {
           "Voice": "Hydrogen",
           "Display": "Hydrogen"
        }
     },
     {
        "id": "53",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "50",
        "question": {
           "Voice": "What is the more common name for Nitrous Oxide? �",
           "Display": "What is the more common name for Nitrous Oxide? �"
        },
        "answer": {
           "Voice": "Laughing gas",
           "Display": "Laughing gas"
        }
     },
     {
        "id": "54",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "75",
        "question": {
           "Voice": "In computing, how many bits are in a byte?",
           "Display": "In computing, how many bits are in a byte?"
        },
        "answer": {
           "Voice": "Eight",
           "Display": "Eight"
        }
     },
     {
        "id": "55",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "50",
        "question": {
           "Voice": "Who discovered Penicillin?",
           "Display": "Who discovered Penicillin?"
        },
        "answer": {
           "Voice": "Alexander Fleming",
           "Display": "Alexander Fleming"
        }
     },
     {
        "id": "56",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "25",
        "question": {
           "Voice": "Which planet in our solar system is closest to the sun?",
           "Display": "Which planet in our solar system is closest to the sun?"
        },
        "answer": {
           "Voice": "Mercury",
           "Display": "Mercury"
        }
     },
     {
        "id": "57",
        "category": "Science & Technology",
        "locales": "GB#US",
        "difficulty": "25",
        "question": {
           "Voice": "What subject did Mark Zuckerburg study at university?",
           "Display": "What subject did Mark Zuckerburg study at university?"
        },
        "answer": {
           "Voice": "Computer Science",
           "Display": "Computer Science"
        }
     },

And here's my attempt:

var allQuiz= myObject;

var easyQuiz =[];
var mediumQuiz =[];
var hardQuiz =[];
var veryhardQuiz =[];


for(let x=0;x<allQuiz.length;x++){

    if(allQuiz[x].difficulty==25){
        let tmp = [];
        tmp.push((allQuiz[x]).id);
    tmp.push((allQuiz[x]).question.Display);
    tmp.push((allQuiz[x]).answer.Display);
    easyQuiz.push(tmp);
}
else if(allQuiz[x].difficulty==50){
    let tmp =[];
    tmp.push((allQuiz[x]).id);
    tmp.push((allQuiz[x]).question.Display);
    tmp.push((allQuiz[x]).answer.Display);
    mediumQuiz.push(tmp);

}
else if(allQuiz[x].difficulty==75){
    let tmp =[];
    tmp.push((allQuiz[x]).id);
    tmp.push((allQuiz[x]).question.Display);
    tmp.push((allQuiz[x]).answer.Display);
    hardQuiz.push(tmp);

}
else {
    let tmp = [];
    tmp.push((allQuiz[x]).id);
    tmp.push((allQuiz[x]).question.Display);
    tmp.push((allQuiz[x]).answer.Display);
    veryhardQuiz.push(tmp);
} 
}

However, I have noticed there is a lot of code duplication here, the only factors which change are the quiz category im pushing to , and the difficulty of the question.

How could I go about making this for loop more elegant and or more efficient?

4
  • I think the only thing missing here is the structure of the object, however its pretty huge. I'll put in a portion of it.. Commented Oct 4, 2018 at 17:01
  • 1
    Please share a sample of the structure of object. If it is huge share top 20-30 values Commented Oct 4, 2018 at 17:03
  • I would split the object, create a higher level object that contains difficulty, category and locals, then arrays which are 1 : 1 with member names questions and answers, this will remove a lot of duplication and make your code easier to manage. Commented Oct 4, 2018 at 17:17
  • 1
    Also, if your code works but you're looking for feedback on cleanup and improvement, CodeReview may be a better fit. Commented Oct 4, 2018 at 17:33

3 Answers 3

2

I don't think I can make it any more succinct without sacrificing readability:

var allQuiz= myObject;
var quizzesByDifficulty = { 25: [], 50: [], 75: [], 100: [] };
for(var x in allQuiz)
{
  var quiz = allQuiz[x];
  var quizzes = quizzesByDifficulty[quiz.difficulty];
  quizzes.push([
    quiz.id,
    quiz.question.Display,
    quiz.answer.Display
  ]);
}

If you need each difficulty to be its own array, you can always do:

var easy = quizzesByDifficult[25];
var medium = quizzesByDifficulty[50];
// etc.

EDIT: Of course the above assumes there are only the 4 difficulties available. If that's an assumption you cannot make, you can still modify the code to account for that:

var allQuiz= myObject;
var quizzesByDifficulty = {};
for(var x in allQuiz)
{
  var quiz = allQuiz[x];

  if (!quizzesByDifficulty[quiz.difficulty]) {
    quizzesByDifficulty[quiz.difficulty] = [];
  }

  var quizzes = quizzesByDifficulty[quiz.difficulty];
  quizzes.push([
    quiz.id,
    quiz.question.Display,
    quiz.answer.Display
  ]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

allQuiz/myObject is actually an array (it's not obvious from OP's structure dump or var name choice).
@ggorlen, Yep, I saw from the original post. Realistically, even if allQuiz was an object indexed by some arbitrary key, the code would still work. It would just use the keys to index into allQuiz. The only caveat for arrays is that iteration cannot be assumed in a particular order. If order is important, the classic loop would need to be used or a .reduce(). At least that's what I assume you are addressing.
1

array.reduce is a handy function for such data transformation tasks as this. The idea is to create an object keyed by difficulty mapped to an array of values. At the end, the resulting object can be split into your four desired structures or used as-is (possibly with a key mapping from difficulty number to difficulty word, if you wish).

var allQuiz = [{ "id": "41", "category": "TV & Movies", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "Which fictional city is the home of Batman?", "Display": "Which fictional city is the home of Batman?" }, "answer": { "Voice": "Gotham City", "Display": "Gotham City" } }, { "id": "42", "category": "TV & Movies", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "The Hunchback of Notre Dame was also known as?", "Display": "The Hunchback of Notre Dame was also known as?" }, "answer": { "Voice": "Quasimodo", "Display": "Quasimodo" } }, { "id": "43", "category": "TV & Movies", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "The title role of the 1990 movie Pretty Woman was played by which actress?", "Display": "The title role of the 1990 movie Pretty Woman was played by which actress?" }, "answer": { "Voice": "Julia Roberts", "Display": "Julia Roberts" } }, { "id": "44", "category": "TV & Movies", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "Which Tom Hanks movie won the Academy Award for Best Picture in 1994?", "Display": "Which Tom Hanks movie won the Academy Award for Best Picture in 1994?" }, "answer": { "Voice": "Forrest Gump", "Display": "Forrest Gump" } }, { "id": "45", "category": "TV & Movies", "locales": "GB#US", "difficulty": "100", "question": { "Voice": "Jonny Depp starred as Jack Sparrow in which series of movies?", "Display": "Jonny Depp starred as Jack Sparrow in which series of movies?" }, "answer": { "Voice": "Pirates of the Caribbean", "Display": "Pirates of the Caribbean" } }, { "id": "46", "category": "TV & Movies", "locales": "GB#US", "difficulty": "100", "question": { "Voice": "Marion Crane is the tragic figure in which cult horror film?", "Display": "Marion Crane is the tragic figure in which cult horror film?" }, "answer": { "Voice": "Psycho", "Display": "Psycho" } }, { "id": "47", "category": "Science & Technology", "locales": "GB#US", "difficulty": "25", "question": { "Voice": "Alexander Graham Bell invented which communication tool?", "Display": "Alexander Graham Bell invented which communication tool?" }, "answer": { "Voice": "Telephone", "Display": "Telephone" } }, { "id": "48", "category": "Science & Technology", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "Steve jobs was the founder of which tech giant?", "Display": "Steve jobs was the founder of which tech giant?" }, "answer": { "Voice": "Apple", "Display": "Apple" } }, { "id": "49", "category": "Science & Technology", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "Which year was Amazon founded?", "Display": "Which year was Amazon founded?" }, "answer": { "Voice": "1994", "Display": "1994" } }, { "id": "50", "category": "Science & Technology", "locales": "GB#US", "difficulty": "100", "question": { "Voice": "What is the natural habitat of an arboreal creature?", "Display": "What is the natural habitat of an arboreal creature?" }, "answer": { "Voice": "Trees", "Display": "Trees" } }, { "id": "51", "category": "Science & Technology", "locales": "GB#US", "difficulty": "25", "question": { "Voice": "What is a geiger counter used to detect?", "Display": "What is a geiger counter used to detect?" }, "answer": { "Voice": "Radiation", "Display": "Radiation" } }, { "id": "52", "category": "Science & Technology", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "What element on the periodic table has the chemical symbol H?", "Display": "What element on the periodic table has the chemical symbol H?" }, "answer": { "Voice": "Hydrogen", "Display": "Hydrogen" } }, { "id": "53", "category": "Science & Technology", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "What is the more common name for Nitrous Oxide? �", "Display": "What is the more common name for Nitrous Oxide? �" }, "answer": { "Voice": "Laughing gas", "Display": "Laughing gas" } }, { "id": "54", "category": "Science & Technology", "locales": "GB#US", "difficulty": "75", "question": { "Voice": "In computing, how many bits are in a byte?", "Display": "In computing, how many bits are in a byte?" }, "answer": { "Voice": "Eight", "Display": "Eight" } }, { "id": "55", "category": "Science & Technology", "locales": "GB#US", "difficulty": "50", "question": { "Voice": "Who discovered Penicillin?", "Display": "Who discovered Penicillin?" }, "answer": { "Voice": "Alexander Fleming", "Display": "Alexander Fleming" } }, { "id": "56", "category": "Science & Technology", "locales": "GB#US", "difficulty": "25", "question": { "Voice": "Which planet in our solar system is closest to the sun?", "Display": "Which planet in our solar system is closest to the sun?" }, "answer": { "Voice": "Mercury", "Display": "Mercury" } }, { "id": "57", "category": "Science & Technology", "locales": "GB#US", "difficulty": "25", "question": { "Voice": "What subject did Mark Zuckerburg study at university?", "Display": "What subject did Mark Zuckerburg study at university?" }, "answer": { "Voice": "Computer Science", "Display": "Computer Science" } },];

const quizzes = allQuiz.reduce((a, e) => {
  if (!a[e.difficulty]) {
    a[e.difficulty] = [];
  }
  
  a[e.difficulty].push([e.id, e.question.Display, e.answer.Display]);
  return a;
}, {});

const easyQuiz = quizzes["25"];
const mediumQuiz = quizzes["50"];
const hardQuiz = quizzes["75"];
const veryHardQuiz = quizzes["100"];

console.log(easyQuiz);
console.log(mediumQuiz);
console.log(hardQuiz);
console.log(veryHardQuiz);

Comments

0

I assume that allQuiz will be an array. Yes, like you mentioned this can be optimised a lot.

const allQuiz = [{
  id: 1,
  question: {
    Display: 'abc'
  },
  answer: {
    Display: '123'
  },
  difficulty: 25
}];

const sortedQuiz = {
  easyQuiz: [],
  mediumQuiz: [],
  hardQuiz: [],
  veryhardQuiz: [],
}

allQuiz.reduce((acc, quiz) => {
  let category;

  // Following if..else can also be pulled out into a seperate function
  if (quiz.difficulty === 25) {
    category = acc.easyQuiz;
  } else if (quiz.difficulty === 50) {
    category = acc.mediumQuiz;
  } else if (quiz.difficulty === 75) {
    category = acc.hardQuiz;
  } else {
    category = acc.veryhardQuiz;
  }

  category.push([quiz.id, quiz.question.Display, quiz.answer.Display]);

  return acc;
}, sortedQuiz)


const appDiv = document.getElementById('app');
appDiv.innerHTML = `<p>${JSON.stringify(sortedQuiz)}</p>`;
<div id="app"></div>

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.