【发布时间】:2019-04-17 14:33:49
【问题描述】:
我有一个数组对象,一个
a.b = [1,4,3]
a.c = ["a","b","c"]
我需要按“b”的相反顺序对a进行排序,这样新对象就会是
d.b = [4,3,1]
d.c = ["b","c","a"]
我还需要排序产生的索引数组:
i = [1,2,0]
请建议使用 lodash,谢谢。 哦
【问题讨论】:
标签: sorting object indexing lodash
我有一个数组对象,一个
a.b = [1,4,3]
a.c = ["a","b","c"]
我需要按“b”的相反顺序对a进行排序,这样新对象就会是
d.b = [4,3,1]
d.c = ["b","c","a"]
我还需要排序产生的索引数组:
i = [1,2,0]
请建议使用 lodash,谢谢。 哦
【问题讨论】:
标签: sorting object indexing lodash
您可以使用Schwartzian transform 将当前索引和来自b 的数值添加到使用_.map() 的[value, index] 元组数组中,使用_.orderBy() 根据值(0 index),然后再次提取带有_.map()的原始索引(1个索引)。现在您可以根据索引数组映射b 和c(其他属性),并返回新的排序对象。
// order an array by an array of indexes
const mapByIndex = (arr, indexes) => _.map(arr, (_, idx) => arr[indexes[idx]])
const fn = (sortKey, o) => {
const i = _(o[sortKey])
.map((n, i) => [n, i]) // store the current index in tuples
.orderBy('0') // sort the tuples by the number from b
.map('1') // extract the original index
.value()
return _.assign({ i }, _.mapValues(o, v =>
_.isArray(v) ? mapByIndex(v, i) : v
))
}
const obj = {
b: [1,4,3],
c: ["a","b","c"]
}
const result = fn('b', obj)
const i = result.i
const d = _.omit(result, 'i')
console.log(d)
console.log(i)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
【讨论】:
i 数组的对象。你从结果中提取它。函数需要以组合的方式返回它们,因为函数只能返回单个值。
以下是 Ori Drori 对 coffeescript 的优雅解决方案的适度翻译(如果成功的话):
a = {}
a.b = [1, 4, 3]
a.c = [ "a", "b", "c"]
mapByIndex = (arr, indexes) -> _.map(arr, (_, idx) -> arr[indexes[idx]])
i = _.map(a.b, fct = (n, i) -> [n, i])
i = _.sortBy(i,"0")
i = _.map(i, "1")
i = i.reverse()
i = _.mapValues(a, fct = (v) -> if _.isArray(v) then mapByIndex(v, i) else v)
debug _.keys(i) # b,c
debug _.values(i) # 4,3,1,b,c,a
debug i.b # 4,3,1
debug i.c # b,c,a
【讨论】: