根据另一个Array的顺序对Array进行排序 [英] Sorting an Array according to the order of another Array

查看:196
本文介绍了根据另一个Array的顺序对Array进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小如下的数组:

I have an array with sizes like this:

var arr = [
  'small',
  'small',
  'small',
  'small',
  ...
  'medium',
  'medium',
  'medium',
  'medium',
  ...
  'big',
  'big',
  ...
];

我需要根据此订单重新组织此数组:

I need to reorganize this array according to this order:

var order = ['small', 'small', 'medium', 'medium', 'big'];

所以结果最终会是这样的:

So the result ends up being something like this:

var arr = [
  'small',
  'small',
  'medium',
  'medium',
  'big',

  'small',
  'small',
  'medium',
  'medium',
  'big'

  ...
];

我知道其他类似的问题,但到目前为止我找不到任何东西。我不确定如何处理这个问题。我在想 sort 应该做什么但是我要测试什么?看起来很简单,但我卡住了,不知道从哪里开始。任何提示?

I'm aware of other similar questions in SO but I couldn't find anything so far. I'm unsure how to approach this. I was thinking sort should do but what do I test for? It seems simple but I'm stuck, don't know where to begin. Any hints?

推荐答案

好吧,我最终得到了这个有效的解决方案:

Well, I finally ended up with this solution that works:

function orderBy(arr, order) {
  var result = [],
      i = 0, len = arr.length,
      index;

  while (result.length < len) {
    index = arr.indexOf(order[i]);
    result.push(arr[index]);
    arr.splice(index, 1);
    i = i >= order.length-1 ? 0 : ++i;
  }

  return result;
}

它修改了原始数组,但没关系。

It modifies the original array but that's ok.

演示: http://jsbin.com/umizat/1/edit

这篇关于根据另一个Array的顺序对Array进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆