Lodash-按数组中的位置排序

时间:2018-10-11 12:48:21

标签: javascript lodash

我有一个对象数组

let myArray = [
    {
        id: 'first',
        name: 'john',
    },
    {
        id: 'second',
        name: 'Emmy',
    },
    {
        id: 'third',
        name: 'Lazarus',
    }
]

和一个数组

let sorter = ['second', 'third', 'first']

我想使用lodash排序方法根据对象在sorter中的位置对我的对象进行排序。 这样输出将是

let mySortedArray = [
    {
        id: 'second',
        name: 'Emmy',
    },
    {
        id: 'third',
        name: 'Lazarus',
    },
    {
        id: 'first',
        name: 'john',
    }
]

有可能这样做吗?

4 个答案:

答案 0 :(得分:3)

您可以使用mapfind来实现:

let myArray = [
  {
    id: "first",
    name: "john"
  },
  {
    id: "second",
    name: "Emmy"
  },
  {
    id: "third",
    name: "Lazarus"
  }
];

let sorter = ["second", "third", "first"];

let mySortedArray = sorter.map(x => myArray.find(y => y.id === x));

console.log(mySortedArray);

答案 1 :(得分:2)

使用lodash,您可以使用_.sortBy

let myArray = [
    {
        id: 'first',
        name: 'john',
    },
    {
        id: 'second',
        name: 'Emmy',
    },
    {
        id: 'third',
        name: 'Lazarus',
    }
]

let sorter = ['second', 'third', 'first']

console.log(_.sortBy(myArray,(i) => {return sorter.indexOf(i.id)})) 
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>

答案 2 :(得分:0)

如果您想就地对数组进行排序,不需要Lodash,则可以使用原始JavaScript轻松完成

let myArray = [
    {
        id: 'first',
        name: 'john',
    },
    {
        id: 'second',
        name: 'Emmy',
    },
    {
        id: 'third',
        name: 'Lazarus',
    }
]

let sorter = ['second', 'third', 'first']

//create a lookup table (map) to save looking through the array
const sortLookup = new Map(); 
//populate with element as key - index as value
sorter.forEach((id, index) => sortLookup.set(id, index));

//sort using the indexes of sorter 
myArray.sort((a, b) => sortLookup.get(a.id) - sortLookup.get(b.id))

console.log(myArray)

这使用的是a Map,但是使用普通的JavaScript对象{}可以轻松实现相同的目的。您甚至不需要预先计算查找myArray.sort((a, b) => sorter.indexOf(a.id) - sorter.indexOf(b.id))就能得到完全相同的输出,但这意味着您不必遍历sorter一次即可获得O(n)的复杂性, O(n^m)O(n^n)(如果两个数组的长度相同)

答案 3 :(得分:0)

由于在index中有一个sorter数组,因此可以_.keyBy主数组,然后使用sorter按索引访问:

let myArray = [ { id: 'first', name: 'john', }, { id: 'second', name: 'Emmy', }, { id: 'third', name: 'Lazarus', } ]
let sorter = ['second', 'third', 'first']

const idMap = _.keyBy(myArray, 'id')
const result = _.map(sorter, x => idMap[x])

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

这应该会更好,因为您先执行idMap once然后执行access it by index