根据另一个单词数组对单词数组进行排序

时间:2018-12-19 14:48:48

标签: javascript typescript

我有一个像这样的数组:

unorderedArr = ['pear', 'apple', 'banana', 'peach', 'pineapple'];

我想基于另一个给定的数组来排序该数组,如下所示:

order = ['peach', 'apple', 'pineapple']

首选结果将是:

orderedArr = ['peach', 'apple', 'pineapple', 'banana', 'pear'];

将不在顺序数组中的单词放置在哪个索引上没有关系。不能保证order数组中的单词会在无序数组中

当前代码解决方案

我尝试使用这样的switch语句:

const orderedArr = []
unorderedArr.forEach(word => {
  switch (word) {
    case 'peach':
      orderedArr.push(word);
      break;

    case 'apple':
      orderedArr.push(word);
      break;

    case 'pineapple':
      orderedArr.push(word);
      break;

    default:
      orderedArr.push(word);
      break;
    }
});

但是我发现switch语句不会首先检查第一种情况。

3 个答案:

答案 0 :(得分:3)

我认为没有简单的非编程方式可以做到这一点。您需要的是一种能够产生所需结果的算法,如下所示:

function partialOrder(preferences, data)
{
  var result, reminder;

  result = [];

  // find preferences and put them into result
  preferences.forEach((name) => {
    result = result.concat(
      data.filter((d) => d.name === name)
    );
  });

  // find remaining data not in preferences
  reminder = data.filter((item) =>
    preferences.indexOf(item.name) === -1
  );

  return result.concat(reminder);
}

var preferences = [ "peach", "pear", "pineapple", "<alien-fruit>" ];
var data = [
  { "name": "apple", "image_url": "xApple" },
  { "name": "pineapple", "image_url": "xPineapple" },
  { "name": "peach", "image_url": "xPeach" },
  { "name": "pear", "image_url": "xPear" },
  { "name": "banana", "image_url": "xBanana" }
];

console.log(partialOrder(preferences, data));

答案 1 :(得分:3)

您可以将对象用于排序顺序,将默认值用于未排序的项目。

var array = ['pear', 'apple', 'banana', 'peach', 'pineapple'],
    wanted = ['peach', 'apple', 'pineapple'],
    order = Object.assign({ default: Infinity }, ...wanted.map((v, i) => ({ [v]: i + 1 })));
    
array.sort((a, b) => (order[a] || order.default) - (order[b] || order.default));

console.log(array);

答案 2 :(得分:2)

以简单的逻辑尝试;

var finalArray = [];

//loop over order array
for(var i=0; i<order.length; i++)   
{             
   //if order array element present into un-order array push in new array
   //this will ensure that in finalArray elements stays in order                  
   if(unordedArr.indexOf(order[i]) > -1)
       finalArray.push(order[i]);                                    
}

//loop over un-order array
for(var i=0; i<unordedArr.length; i++)    
{                    
   //if in final array the element is not present then enter it again  
   //which means the rest of the elements need to inserted
   if(finalArray.indexOf(unordedArr[i]) == -1)
   {
        finalArray.push(unordedArr[i]);  
   }
}                            

console.log(finalArray)