根据数组元素的值对数组元素排序

时间:2020-02-25 19:15:23

标签: javascript arrays sorting

我有以下对象数组:

dfAC_Renew['date_difference'] = dfAC_Renew.apply(get_date_difference, x = 'customer_since_date', y = 'renewal_date', axis = 1)

我想根据类型的值对数组元素进行排序。如果type为'choice',我想将元素放置在数组的最后一位,即第四位。如果type为'boolean',则将其放在第三位。如果类型为“选择”,则将其放在第二位。

我知道如何用数值对数组进行排序。

[
  0: {
    id: 1,
    type: 'input'   
  },
  1: {
    id: 2,
    type: 'boolean'   
  },
  2: {
    id: 3,
    type: 'choice'   
  },
  3: {
    id: 1,
    type: 'select'   
  },
]

我无法比较属性值并对其进行排序。

请帮助我。任何帮助将不胜感激。

此致

2 个答案:

答案 0 :(得分:1)

通常,如果需要根据对象的某些字符串属性对数组进行排序,则需要创建另一个代表排序顺序的数组。然后使用indexOf减去索引

const order = ['input', 'select', 'boolean','choice'];

const arr = [
  {
    id: 1,
    type: 'input'   
  },
  {
    id: 2,
    type: 'boolean'   
  },
  {
    id: 3,
    type: 'choice'   
  },
  {
    id: 1,
    type: 'select'   
  },
]

arr.sort((a, b) => order.indexOf(a.type) - order.indexOf(b.type));
console.log(arr)

答案 1 :(得分:1)

如果有

const arr = [
  {
    id: 1,
    type: 'input',
    val: 1
  },
  {
    id: 2,
    type: 'boolean',
    val: 3
  },
  {
    id: 3,
    type: 'choice',
    val: 4,
  },
  {
    id: 1,
    type: 'select',
    val: 2
  },
]

那么这很容易:只需arr.sort((a, b) => a.val - b.val)

由于您没有属性val,因此可以在之前将其设置为:

const typeToValue = {
  input: 1,
  boolean: 3,
  choice: 4,
  select: 2
}
arr.forEach(el => {
  el.val = typeToValue[el.type]
})
arr.sort((a, b) => a.val - b.val)

也许您不想弄脏您的元素,请注意el.val == typeToValue[el.type]

意思是你可以写 arr.sort((a, b)=>typeToValue[a.type] - typeToValue[b.type])

最后,如果您有一个已排序的数组['input', 'select', 'boolean', 'choice'],则可以通过typeToValue将其简单地转换为Array.prototype.reduce对象

const orders = ['input', 'select', 'boolean', 'choice']
const typeToValue = orders.reduce((o, el, i) => (o[el] = i, o), {})

或者如果您不喜欢使用Object.fromEntries

const typeToValue = Object.fromEntries(orders.map((el, i) => [el, i]))

const arr = [{"id":1,"type":"input"},{"id":2,"type":"boolean"},{"id":3,"type":"choice"},{"id":1,"type":"select"}]
const orders = ['input', 'select', 'boolean', 'choice']
const typeToValue1 = orders.reduce((o, el, i) => (o[el] = i, o), {})
const typeToValue2 = Object.fromEntries(orders.map((el, i) => [el, i]))

// just slice to copy array because sort modify in place
console.log(arr.slice(0).sort((a, b)=>typeToValue1[a.type] - typeToValue1[b.type]))
console.log(arr.slice(0).sort((a, b)=>typeToValue2[a.type] - typeToValue2[b.type]))

相关问题