自定义搜索-如何根据数组中的值对数组重新排序

时间:2019-02-22 07:10:04

标签: javascript arrays sorting

让我说我有一个数组

const arr = [
  {
    name: "Baburam",
    relation: "self_owner"
  },
  {
    name: "Prapti",
    relation: "grand_child"
  },
  {
    name: "Sanjay",
    relation: "son"
  },
  {
    name: "Bhagwati",
    relation: "wife"
  },
  {
    name: "maya",
    relation: "mother"
  },
]

我想相对于指定值 relation 重新排列数组,并且此顺序是固定的:

  1. self_owner

  2. 妻子

  3. 母亲

  4. 儿子

  5. 孙子

我怎么能得到这样的结果。 我期望的是:

const arr = [
  {
    name: "Baburam",
    relation: "self_owner"
  },
  {
    name: "Bhagwati",
    relation: "wife"
  },
  ,
  {
    name: "Sanjay",
    relation: "son"
  },
  {
    name: "maya",
    relation: "mother"
  },
  {
    name: "Prapti",
    relation: "grand_child"
  }
  
]

先谢谢了。

4 个答案:

答案 0 :(得分:2)

将订单存储在array中,然后根据index中对象relation的{​​{1}}进行排序

arr

答案 1 :(得分:1)

按照您需要的顺序用'~~~> SOMETHING IS MISSING HERE????个项目创建一个If inmatch = "" Then数组。然后在Sub TRANS2() Dim wsCopy2 As Worksheet Dim wsDest2 As Worksheet Dim i As Integer Dim inrow As Integer Dim inmatch As String Dim inpax As Integer Dim k As Integer Dim outrow As Integer Dim outmatch As String Set wsCopy2 = Workbooks("CargoReport1.xlsx").Worksheets("CargoReport") Set wsDest2 = Workbooks("w1.xlsm").Worksheets("Sheet1") If wsCopy2.Range("c2") > 0 Then inrow = 1000 For i = 2 To inrow inmatch = wsCopy2.Range("d" & i) If inmatch = "" Then Exit For outrow = 1000 For k = 2 To outrow outmatch = wsDest2.Range("A" & k) If outmatch = inmatch Then Exit For End If If outmatch = "" Then wsDest2.Range("A" & k) = inmatch Exit For End If Next If outmatch = inmatch Then Exit For End If End If Next End If End Sub 比较功能

中使用order

relation

答案 2 :(得分:1)

您可以将Array.prototype.reduce()Array.prototype.find()组合使用

代码:

const arr = [{name: "Baburam",relation: "self_owner"},{name: "Prapti",relation: "grand_child"},{name: "Sanjay",relation: "son"},{name: "Bhagwati",relation: "wife"},{name: "maya",relation: "mother"}]; 
const order = ['self_owner', 'wife', 'mother', 'son', 'grand_child'];

const result = order.reduce((a, c) => [...a, arr.find(user => user.relation === c)], []);

console.log(result);

答案 3 :(得分:1)

您可以为固定的排序顺序创建一个固定的数组,然后使用其索引进行排序,

checkbox