我需要对用户输入名称Javascript的数组顺序进行排序

时间:2018-07-18 17:00:09

标签: javascript arrays sorting

它应该对数组进行排序,从数组中删除重复的名称,并在右侧的文本区域中显示名称。输出:字母顺序名称列表,没有重复的名称。

function process() {
  var output = "";
  var inputlistNames = (document.getElementById('input').value);
  var list = inputlistNames.split('\n');
  var arr = inputlistNames.split('\n');
  var list = new Array(arr);
  list.sort();
  var listN = new Array(removeDuplicateUsingFilter(list));
  outputDiv = listN;
  document.getElementById('output').innerHTML = outputDiv;
}


function removeDuplicateUsingFilter(list) {
  var unique_array = [];
  for (var i = 0; i < list.length; i++) {
    if (unique_array.indexOf(list[i]) == -1) {
      unique_array.push(list[i])
    }
  }
  return unique_array;
}
<h1>list of names</h1>
<textarea id="input" rows="16" cols="20"></textarea>
<button type="button" onclick="process()">Remove Duplicates</button>
<textarea id="output" rows="16" cols="20"></textarea>

3 个答案:

答案 0 :(得分:1)

您可以使用Map,它是类型证明,可以防止使用Array#indexOf一次又一次地迭代。

function removeDuplicateUsingFilter(list) {
   filtered = list.filter(function (a) {
     if (!this.has(a.toLowerCase())) {
        this.set(a, true);
        return true;
     }
   }, new Map);
  return filtered.sort()
}

a = ["genesis", "genesis", "ruben", "adeline", "ruben", "adeline", 
"fausto", "lauren", "zeke", "samantha", "Samantha", "Genesis"]

console.log(removeDuplicateUsingFilter(a))

//output: ["adeline", "fausto", "genesis", "lauren", "ruben", "samantha", "zeke"]

答案 1 :(得分:1)

尝试一下:

const words = [
  "genesis", 
  "genesis", 
  "ruben", 
  "adeline", 
  "ruben", 
  "adeline", 
  "fausto", 
  "lauren", 
  "zeke", 
  "samantha", 
  "Samantha", 
  "Genesis"
 ];

const sorted = Object.keys(words.reduce((res, word) => {
  return {...res, [word]:word}
}, {})).sort((a, b) => a.localeCompare(b));

console.log(sorted);

localCompare()函数具有许多控制排序的选项,并且可以处理以下情况:

 const arr = [ "1", "10", "2" , "1A", "10a", "2a", "10A"];
 arr.sort((a,b)=>a.localeCompare(b, 'en', {numeric: true}));

答案 2 :(得分:0)

list.filter(
    (elem) => {
         return list.find(elem) === -1 ? true : false;
    }
)
.sort(
    (a,b) => {
         return a > b ? 1 : -1;
    }
);

这应该有效