Good day. It is necessary to write a function that filters students by group. The function should return only those students who study in the specified group.

I can not understand what exactly to use here. Thank you in advance.

Source:

var groupmates = [ { "name": "Andrey", "group": "912-2", "age": 19, "marks": [4, 3, 5, 5, 4] }, { "name": "Artem", "group": "912-1", "age": 18, "marks": [3, 2, 3, 4, 3] }, { "name": "Lisa", "group": "912-2", "age": 19, "marks": [3, 5, 4, 3, 5] }, { "name": "Irina", "group": "912-1", "age": 18, "marks": [5, 5, 5, 4, 5] } ]; console.log(groupmates); var rpad = function(str, length) { // js не поддерживает добавление нужного количества символов // справа от строки то есть аналога ljust из языка Python здесь нет str = str.toString(); // преобразование в строку while (str.length < length) str = str + ' '; // добавление пробела в конец строки return str; // когда все пробелы добавлены, возвратить строку }; var printStudents = function(students){ console.log( rpad("Name", 15), rpad("Group", 8), rpad("Age", 8), rpad("Marks", 20) ); // был выведен заголовок таблицы for (var i = 0; i<=students.length-1; i++){ // в цикле выводится каждый экземпляр студента console.log( rpad(students[i]['name'], 15), rpad(students[i]['group'], 8), rpad(students[i]['age'], 8), rpad(students[i]['marks'], 20) ); } console.log('\n'); // добавляется пустая строка в конце вывода }; printStudents(groupmates); 

    2 answers 2

    Use Array.prototype.filter :

     // Функция-фильтр var filterStudents = function (students, group) { return students.filter(function(student) { return (student.group == group); }); }; // Использование var groupmates = [/* ... */]; console.dir(filterStudents(groupmates, '912-1')); 

    And here is a working example on JSFiddle.

    • If I need to enter the group number, and not immediately call it, do I need to use input? - R.Lin
    • If we are talking about the browser, then prompt . Well, this is not related to the actual filtering ;) - Dmitriy Simushev
    • Anyway for some reason does not display. There was an attempt to replace console.dir with console.log - nothing ( - R.Lin
    • @ R.Lin you're lying all, the code works as it should. Proof: jsfiddle.net/qgsnhm5p - Dmitriy Simushev
    • aah, everything, I found an error in my code) thanks a lot) - R.Lin

     let groupmates = [ { "name": "Andrey", "group": "912-2", "age": 19, "marks": [4, 3, 5, 5, 4] }, { "name": "Artem", "group": "912-1", "age": 18, "marks": [3, 2, 3, 4, 3] }, { "name": "Lisa", "group": "912-2", "age": 19, "marks": [3, 5, 4, 3, 5] }, { "name": "Irina", "group": "912-1", "age": 18, "marks": [5, 5, 5, 4, 5] } ], select = document.querySelector('#select'), log = document.querySelector('#log'); // Заполняем select уникальными группами let tmp = new Set(), res = ''; groupmates.forEach(e => tmp.add(e.group)); select.innerHTML = '<option>' + Array.from(tmp).join('</option><option>') + '</optino>'; select.addEventListener('change', function(e){ let option = this.selectedOptions[0]; render(filter(option.innerHTML)); }); // Фильтруем группы function filter(groupId){ return groupmates.filter(g => g.group === groupId); } function render(data){ let res = ''; data.forEach(s => res += `Имя: ${s.name}<br />Возраст: ${s.age}<br />Отметки: ${s.marks.join`, `}<br /><br />`); log.innerHTML = res; } 
     <select id='select'></select><br /> <div id='log'></div> 

    • When I try to output to the console, it gives an error. Tell me, please, what to do. - R.Lin
    • @ R.Lin, telepath mode only for those who bought a subscription. The rest must be reported at least that the text of the error. - user207618