An array of data comes in - [JavaScript, Python, C ++, Java, PHP, HTML, CSS]. You need to sort the array in order to get [Javascript, CSS, HTML, Java, Python, C ++] at the output. I can’t do the algorithm in any way, so that I don’t additionally assign a digital index to each element and sort them simply by numbers.
Closed due to the fact that the issue is too general for participants user207618, pavel , Streletz , lexxl , Ivan Pshenitsyn 17 Aug '16 at 11:38 .
Please correct the question so that it describes the specific problem with sufficient detail to determine the appropriate answer. Do not ask a few questions at once. See “How to ask a good question?” For clarification. If the question can be reformulated according to the rules set out in the certificate , edit it .
|
1 answer
Here is an efficient algorithm in ES6 syntax.
See the output in the browser console by opening it before running the script.
var order = ["JavaScript", "Python", "C++", "Java", "PHP", "HTML", "CSS"]; var data = []; for (var q=0; q<10; ++q) { data.push({lang: order[Math.random()*order.length|0], val: q}) } console.table(data) function orderData(data, order) { var temp = Object.create(null), res = []; order = [].concat(order); for (var key of order) { temp[key] = []; } for (var x of data) { if (!temp[x.lang]) { order.push(x.lang); temp[x.lang] = []; } temp[x.lang].push(x); } for (var key of order) { //temp[key].sort(выполнить сортировку по дополнительным параметрам) res.push(...temp[key]); } return res; } console.table(orderData(data, order)); console.table(orderData([{lang: 'new', val: -1}].concat(data), order)); console.log(order); - and what is the meaning of the
order = [].concat(order);? overwrite the global variable on the new self? - Grundy - You just assign it to yourself, and somehow the meaning in the copy is lost :-) - Grundy
- @Grundy, nea:
order.push(x.lang);The meaning of the copy is not to corrupt the array in the calling code. - Qwertiy ♦ - But now you spoil it :-) you assign a copy to the same global variable - Grundy
|
sort- it takes the sort function. - user207618function mySort(arr) {return ['Javascript', 'CSS', 'HTML', 'Java', 'Python', 'C++'];}If it does not work, then specify the question. - Yaant 4:34 pm