用lodash按包含的数组对数组的对象进行排序,然后找到索引数组

时间:2019-04-17 14:33:50

标签: 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,谢谢。

2 个答案:

答案 0 :(得分:0)

您可以Schwartzian transform使用b_.map()中的当前索引和数值添加到[value,index]元组的数组中,并以_.orderBy()进行排序根据值(索引0)对元组进行排序,然后再次使用_.map()(1索引)提取原始索引。现在,您可以根据索引数组映射bc(其他属性),并返回新的排序对象。

// 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>

答案 1 :(得分:0)

如果成功,这是Ori Drori对咖啡 的优雅解决方案的适度近似翻译:

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