按某个单词对列表进行排序

时间:2020-12-21 10:48:38

标签: javascript arrays sorting

我需要按特定单词对数组列表进行排序。任何帮助,将不胜感激。谢谢。

 List=[microphone,phone,telephone,mobilephone]
    
 word="pho"

答案应该是,

<块引用>

answer=[电话ne,telephone,microphone,mobilephone]< /p>

2 个答案:

答案 0 :(得分:5)

您可以使用 indexOf() 获取索引号并将其传递给 sort 方法。

const list = ["microphone", "phone", "telephone", "mobilephone"];

const sortBySubstring = (words, match) => {
  return words.sort((a, b) => {
    return a.indexOf(match) - b.indexOf(match);
  });
}

const result = sortBySubstring(list, "pho");

console.log(result);

编辑:

如果您的列表中有一个不包含子字符串的单词,它将被放置在数组的开头。有一些方法可以改变这种行为。

首先你可以用includes()检查它是否存在,如果它不存在将它放在数组的末尾

const list = ["microphone", "phone", "telephone", "mobilephone", "telemobile"];

const sortBySubstring = (words, match) => {
  return words.sort((a, b) => {
    if(!a.includes(match) || !b.includes(match)) return 1;
    
    return a.indexOf(match) - b.indexOf(match);
  });
}

const result = sortBySubstring(list, "pho");

console.log(result);

另一种选择是 filter() 去掉不包含给定子字符串的单词

const list = ["microphone", "phone", "telephone", "mobilephone", "telemobile"];

const sortBySubstring = (words, match) => {
  const contains = words.filter((word) => word.includes(match));

  return contains.sort((a, b) => {
    return a.indexOf(match) - b.indexOf(match);
  });
}

const result = sortBySubstring(list, "pho");

console.log(result);

答案 1 :(得分:2)

比 Reyno 的答案长一点,但它将数组中不存在的字符串移到末尾。

// The following function was taken from here: https://stackoverflow.com/questions/16096872/how-to-sort-2-dimensional-array-by-column-value (answer by jahroy)
function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] < b[1]) ? -1 : 1;
    }
}


function sortByWord(list, word) {
    // put data into 2d array (x) with array item and indexOf search term
  var x = [];
  var doesntContainWord = [];
  for (var i = 0; i < list.length; i++) {
    if (list[i].indexOf(word) == -1) {
        // if the search word doesn't exist, push to array
      doesntContainWord.push(list[i]);
    } else {
        x[i] = [list[i], list[i].indexOf(word)];
    }
  }
  doesntContainWord.sort();
  // now sort var x by second col.
  x.sort(compareSecondColumn);
  // now dump values back into array and return them
  var toReturn = [];
  for (var i = 0; i < x.length; i++)     {
    toReturn[i] = x[i][0];
  }
  return toReturn.concat(doesntContainWord);
}

var data = ["microphone", "phone", "telephone", "mobilephone", "cat", "animal"];

console.log(sortByWord(data, "pho"))