如何根据另一个数组的值对一个数组的值进行排序

时间:2018-09-19 06:08:42

标签: javascript angularjs

list1 = [{name: 'apple'}, {name: 'pear'}, {name: 'banana'}]
list2 = ['banana', 'apple', 'pear']

期望

list1 = [{name: 'banana'}, {name: 'apple'}, {name: 'pear'}]

如何通过angularjs ng-repeat或JS制作list2并对list1进行排序

5 个答案:

答案 0 :(得分:1)

还有地图解决方案

var list1=[{
  name: 'apple'
}, {
  name: 'pear'
}, {
  name: 'banana'
}];
var list2 = ['banana', 'apple', 'pear'];

list1 = list2.map(x=>{
return {name:x};
});

console.log(list1);

答案 1 :(得分:0)

您可以使用数组list2的索引来获取用于排序的数值:

var list1 = [{
  name: 'apple'
}, {
  name: 'pear'
}, {
  name: 'banana'
}]
var list2 = ['banana', 'apple', 'pear'];
list1.sort(function(a, b) {
  return list2.indexOf(a.name) - list2.indexOf(b.name);
});
console.log(list1);

答案 2 :(得分:0)

尝试一下:

#pragma once

#include <whiteboard/LaunchableModule.h>
#include <whiteboard/ResourceClient.h>

class UartClient FINAL : private whiteboard::ResourceClient,
                         public whiteboard::LaunchableModule

{
public:
    /** Name of this class. Used in StartupProvider list. */
    static const char* const LAUNCHABLE_NAME;
    UartClient();
    ~UartClient();

private:
    /** @see whiteboard::ILaunchableModule::initModule */
    virtual bool initModule() OVERRIDE;

    /** @see whiteboard::ILaunchableModule::deinitModule */
    virtual void deinitModule() OVERRIDE;

    /** @see whiteboard::ILaunchableModule::startModule */
    virtual bool startModule() OVERRIDE;

    /** @see whiteboard::ILaunchableModule::stopModule */
    virtual void stopModule() OVERRIDE;
};

答案 3 :(得分:0)

根据您拥有的和想要拥有的东西。这就是你的方式。

list1 = [{name: 'apple'}, {name: 'pear'},{name: 'banana'}];
list2 = ['banana', 'apple', 'pear'];
var result = [];
function getData(){
list2.forEach(function(e){
  let obj=list1.find(element=>element['name'] === e);
  result.push(obj);
})
console.log(result);
}
getData();
// In case you want to preserve with list1
list1.sort(function(a, b){  
  return list2.indexOf(a.name) - list2.indexOf(b.name);
});
console.log(list1)

现在您可以在result中使用ng-repeat了;

答案 4 :(得分:0)

使用compare函数,如下所示:

var list1 = [{name: 'apple'}, {name: 'pear'}, {name: 'banana'}];
var list2 = ['banana', 'apple', 'pear'];

function comp(a, b) {
  return list2.indexOf(a.name) - list2.indexOf(b.name);
}

list1.sort(comp);

console.log(list1);