JavaScript сортировать / перемешивать при сохранении определенного шаблона - PullRequest
0 голосов
/ 30 января 2019

У меня есть вариант использования примерно так.

  1. У меня есть база вопросов.

  2. Каждый вопрос относится к одному типу вопроса.

  3. Мне нужно показать вопросный лист (Вопросы перемешать), где вопросы приходят из одного типа за другим.

const question_types = [
{id:1, type:"science"},
{id:2, type:"history"},
{id:3, type:"current affairs"},
{id:4, type:"maths"}
]

const questions = [
{id:1,question:"World War I began in which year?",type:2},
{id:2,question:"Adolf Hitler was born in which country?",type:2},
{id:3,question:"Which general famously stated 'I shall return'?",type:2},
{id:4,question:"The Magna Carta was published by the King of which country? ",type:2},

{id:5,question:"10 + 12? ",type:4},
{id:6,question:"10 - 12? ",type:4},
{id:7,question:"10 + 192? ",type:4},

{id:8,question:"Who is the prime minister of Canada?",type:3},
{id:9,question:"Who is the prime minister of India?",type:3},
{id:10,question:"Who is the prime minister of UK?",type:3},
{id:11,question:"Who is the prime minister of Sri lanka?",type:3},
{id:12,question:"Who is the president of USA?",type:3},
{id:13,question:"Who is the president of France?",type:3},

{id:14,question:"Name the four states in which matter exists.?",type:1},

]

Это примерный набор данных.Здесь у меня есть

  • Наука - 1 вопрос,
  • Текущие дела - 6 вопросов,
  • Математика - 3 вопроса,
  • История - 4 вопроса

Я бы, кроме сортировки вопроса по этой схеме

Наука, история, текущие дела, математика, история, текущие дела, математика, история, текущие дела, математика, история, текущиедела, текущие дела, текущие дела

Как мне добиться этого с помощью JavaScript?И если вы спросите, что я сделал до сих пор?

Я повторяю в forEach и сначала извлекаю ids.Затем я использую filter для фильтрации по типу и потерял.

Ответы [ 3 ]

0 голосов
/ 30 января 2019

Вот ваш код с небольшим объяснением

let pattern = "science, history, current affairs, maths, history, current affairs, maths ,history, current affairs, maths,history, current affairs, current affairs,current affairs"
//split pattern string
pattern = pattern.split(',').map(type=>type.trim());
//convert eact item in array to its type number id in question_types
pattern = pattern.map(type => (question_types.find(typeItem => typeItem.type === type).id))

function sortQuestions(arr, pattern){
    let resultArr = [];  //array to be returned
    for(let type of pattern){
        //find index of question of desired type
        let questionNo = arr.findIndex(question => question.type === type);
        //push into the resultArr
        resultArr.push(arr[questionNo]);
        //remove it from main array so that it wouldn't repeat
        arr.splice(questionNo,1);
    }
    return resultArr;
}
0 голосов
/ 30 января 2019

const question_types = [
{id:1, type:"science"},			// -> 1
{id:2, type:"history"},			// -> 2
{id:3, type:"current affairs"}, // -> 3
{id:4, type:"maths"}			// -> 4
];

const questions = [
{id:1,question:"World War I began in which year?",type:2},
{id:2,question:"Adolf Hitler was born in which country?",type:2},
{id:3,question:"Which general famously stated 'I shall return'?",type:2},
{id:4,question:"The Magna Carta was published by the King of which country? ",type:2},

{id:5,question:"10 + 12? ",type:4},
{id:6,question:"10 - 12? ",type:4},
{id:7,question:"10 + 192? ",type:4},

{id:8,question:"Who is the prime minister of Canada?",type:3},
{id:9,question:"Who is the prime minister of India?",type:3},
{id:10,question:"Who is the prime minister of UK?",type:3},
{id:11,question:"Who is the prime minister of Sri lanka?",type:3},
{id:12,question:"Who is the president of USA?",type:3},
{id:13,question:"Who is the president of France?",type:3},

{id:14,question:"Name the four states in which matter exists.?",type:1}
];

var ques = questions;
var dynamicappendVal = [];


while(0 < ques.length) {
	for(let i=0;i<question_types.length;i++) {
	  for(let j=0;j<ques.length;j++) {
		if(question_types[i].id == ques[j].type) {
			dynamicappendVal.push(ques[j]);
			ques.splice(ques.indexOf(ques[j]),1);
			break;
		}
	  }
	}
}
console.log(dynamicappendVal);
0 голосов
/ 30 января 2019

Попробуйте, как показано ниже.Перейдите к основному массиву questions и извлеките один за другим вопрос в качестве необходимой последовательности и вставьте в массив sortedQuestions.

const question_types = [
  {id:1, type:"science"},
  {id:2, type:"history"},
  {id:3, type:"current affairs"},
  {id:4, type:"maths"}
];

const questions = [
  {id:1,question:"World War I began in which year?",type:2},
  {id:2,question:"Adolf Hitler was born in which country?",type:2},
  {id:3,question:"Which general famously stated 'I shall return'?",type:2},
  {id:4,question:"The Magna Carta was published by the King of which country? ",type:2},

  {id:5,question:"10 + 12? ",type:4},
  {id:6,question:"10 - 12? ",type:4},
  {id:7,question:"10 + 192? ",type:4},

  {id:8,question:"Who is the prime minister of Canada?",type:3},
  {id:9,question:"Who is the prime minister of India?",type:3},
  {id:10,question:"Who is the prime minister of UK?",type:3},
  {id:11,question:"Who is the prime minister of Sri lanka?",type:3},
  {id:12,question:"Who is the president of USA?",type:3},
  {id:13,question:"Who is the president of France?",type:3},

  {id:14,question:"Name the four states in which matter exists.?",type:1},
];

const sequence = ["science", "history", "current affairs", "maths"];
let sequenceTypes = sequence.map(x => question_types.filter(y => y.type == x)[0]);
let sortedQuestions = [];
let index = 0;

while(questions.length > 0) {
  var i = questions.findIndex(x => x.type == sequenceTypes[index].id);
  if (i != -1) {
    sortedQuestions.push(questions.splice(i, 1)[0]);
  }
  index = (index + 1) % sequenceTypes.length;
}

console.log(sortedQuestions);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...