Last active
November 10, 2017 02:12
-
-
Save allenfantasy/794f4a7693e42a40d467ef74cdba163b to your computer and use it in GitHub Desktop.
sort by another array's order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// arr = [12,3,7] | |
// arr_source = [{id:1, name:'a'}, {id:2, name:'b'}, ..., {id:100, name:'xxxx'}] | |
// sort arr_source based on arr: | |
// [{id: 12, name: 'xx'}, {id: 3, name: 'xxx'}, {id: 7, name: 'xxx'}, …., {id: 100, name: 'xxxx'}] | |
const sortByArr = (targetArr, orderArr) => { | |
let ret = orderArr.slice(0) | |
targetArr.forEach((item,index) => { | |
let orderIndex = orderArr.indexOf(item.id) | |
if (orderIndex > -1) { | |
ret[orderIndex] = item | |
targetArr.splice(index,1) | |
} | |
}) | |
ret = ret.concat(targetArr) | |
return ret | |
} | |
var arr = [12,3,7] | |
var arr_source = [...Array(100).keys()].map( index => ({ id:index, name:`${index}`}) ) | |
var ret = sortByArr(arr_source,arr) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment