如何按两个属性对数组进行排序 - 按字母顺序排列,但最后是空值?

时间:2016-06-09 11:00:05

标签: javascript arrays sorting

我有一个包含对象的数组。

这些对象具有fullname属性和member-id。

虽然fullname始终可用,但如果member-id是潜在会员但尚未注册,则member-id可以为null。

结果应如下所示:

{ id: 1122, name: Adrianna Budzinski }
{ id: 3785, name: Amy Divine }
{ id: 1555, name: Gale Purdue }
{ id: 1920, name: Rex Feng }
{ id: 2010, name: Samella Vizcaino }
{ id: null, name: Bethanie Weaver }
{ id: null, name: Celesta Gullo }
{ id: null, name: Darrick Fort }
{ id: null, name: Edmundo Boulanger }
{ id: null, name: Freddie Lanclos }
{ id: null, name: Gregory Lickteig }
{ id: null, name: Gwendolyn Cuadra }
{ id: null, name: Krystal Brosnahan }
{ id: null, name: Lahoma Pagani }
{ id: null, name: Senaida Risk }
{ id: null, name: Valarie Lopes }

具有id的成员应该按名称排在最前面,而不应该跟随的成员也按名称排序。

到目前为止我所取得的是两个单独的排序函数,但我不知道如何合并它们。

let sortedFriends = friends.sort(function(a, b){
  if(a.name < b.name) return -1;
  if(a.name > b.name) return 1;
  return 0;
});

sortedFriends = sortedFriends.sort(function(a, b){
  if(a.id === null) return 1;
  if(b.id === null) return -1;
  if(a.id === b.id) return 0;
  if(a.id < b.id) return -1 ;
  if(a.id < b.id) return 1;
});

3 个答案:

答案 0 :(得分:2)

您可以按组(idnull)和名称进行排序。

&#13;
&#13;
var array = [{ id: null, name: 'Darrick Fort' }, { id: null, name: 'Edmundo Boulanger' }, { id: 1122, name: 'Adrianna Budzinski' }, { id: null, name: 'Freddie Lanclos' }, { id: null, name: 'Gregory Lickteig' }, { id: null, name: 'Gwendolyn Cuadra' }, { id: 2010, name: 'Samella Vizcaino' }, { id: null, name: 'Bethanie Weaver' }, { id: null, name: 'Celesta Gullo' }, { id: 3785, name: 'Amy Divine' }, { id: null, name: 'Krystal Brosnahan' }, { id: null, name: 'Lahoma Pagani' }, { id: 1920, name: 'Rex Feng' }, { id: 1555, name: 'Gale Purdue' }, { id: null, name: 'Senaida Risk' }, { id: null, name: 'Valarie Lopes' }];

array.sort(function (a, b) {
    return (a.id === null) - (b.id === null) || a.name.localeCompare(b.name);
});

console.log(array);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以将它们组合如下

&#13;
&#13;
import Tkinter,visa,time
from ttk import *

root = Tkinter.Tk
rm = visa.ResourceManager()

# Split port touple into a list
inst_list = []
str_inst = rm.list_resources()
for i in str_inst:
    inst_list.append(i.split(","))

# Convert list into a string and replace it
def delChar(inst,input_inst):
    str_new = ''.join(str(e) for e in inst_list[input_inst])
    find_char = "()u[]"
    for char in find_char:
        inst = str_new.replace(char,"")
    return inst

def delCharIn(list_del):
    str_new = ''.join(str(e) for e in list_del)
    find_char = "()u[]"
    for char in find_char:
        list_del = str_new.replace(char,"")
    return list_del

# List the instruments and choose one
def instControl(inst):
    new_list = []
    for index in range(len(inst)):
        new_list.append(delCharIn(inst[index]))
    return new_list


#keithley = rm.open_resource(instControl(inst_list))

class InterfaceApp(root):
    def __init__(self,parent):
        root.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):

        frInstrument = Tkinter.Frame(width=800, height=200, bg="", 
                                     colormap="new")
        frInstrument.grid(row=0,sticky='EW')

        separator = Tkinter.Frame(width=800, height=2, bd=1, relief='sunken')
        separator.grid(row=1)

        frSettings = Tkinter.Frame(width=800, height = 400, bg="",
                                   colormap="new")
        frSettings.grid(row=3,sticky='EW')

        self.grid_columnconfigure(0,weight=1)
        self.resizable(False,False)

        groupInstrument = Tkinter.LabelFrame(frInstrument,
                                             text="Choose an Instruments",
                                             padx = 5, pady=5)
        groupInstrument.grid(row = 0, column = 1, sticky="EW")
        choices = instControl(inst_list)
        self.choiceVarPower = Tkinter.StringVar()
        self.choiceVarPower.set(choices[0])


        inst1 =Combobox(groupInstrument, values = choices,textvariable = 
                                                    self.choiceVarPower)
        inst1.grid(row=0, column=2,sticky="EW",padx=2,pady=2)



        instLabel1 = Tkinter.Label(groupInstrument, text="Power Supply: ")
        instLabel1.grid(row=0,column=1,sticky='EW')

        instLabel2 = Tkinter.Label(groupInstrument, text="Multimeter: ")
        instLabel2.grid(row=1,column=1,sticky='EW')

        self.choiceVarMulti = Tkinter.StringVar()
        self.choiceVarMulti.set(choices[0])
        inst2 = Combobox(groupInstrument, values=choices, textvariable = 
                            self.choiceVarMulti)
        inst2.grid(row=1,column=2,sticky='EW',padx=2,pady=2)

        but_start = Tkinter.Button(frSettings,text='Run',
                                command=self.Run)
        but_start.grid(row=0,column=1,sticky='EW')
        but_closeInst = Tkinter.Button(frSettings,text="Close all instruments",
                                       command = self.closeInst)
        but_closeInst.grid(row=0,column=2,sticky='EW')

    def W_KPower(scpi_comm):
        return self.keithleyPower.write(":syst:loc")
    def closeInst(self):
        W_KPower(":syst:loc")

    def Run(self):
        self.keithleyPower = rm.open_resource(self.choiceVarPower.get())
        self.keithleyMultimeter = rm.open_resource(self.choiceVarMulti.get())


if __name__ == '__main__':
    app = InterfaceApp(None)
    app.title("")
    app.mainloop()
&#13;
&#13;
&#13;

或使用 String#localeCompare() 方法

进行简化

&#13;
&#13;
var friends = [{  id: 1122,  name: 'Adrianna Budzinski'}, {  id: 3785,  name: 'Amy Divine'}, {  id: 1555,  name: 'Gale Purdue'}, {  id: 1920,  name: 'Rex Feng'}, {  id: 2010,  name: 'Samella Vizcaino'}, {  id: null,  name: 'Bethanie Weaver'}, {  id: null,  name: 'Celesta Gullo'}, {  id: null,  name: 'Darrick Fort'}, {  id: null,  name: 'Edmundo Boulanger'}, {  id: null,  name: 'Freddie Lanclos'}, {  id: null,  name: 'Gregory Lickteig'}, {  id: null,  name: 'Gwendolyn Cuadra'}, {  id: null,  name: 'Krystal Brosnahan'}, {  id: null,  name: 'Lahoma Pagani'}, {  id: null,  name: 'Senaida Risk'}, {  id: null,  name: 'Valarie Lopes'}];

friends.sort(function(a, b) {
  // check id values are equal even the null
  if (a.id === b.id) {
    // compare the name property in that case
    if (a.name < b.name) return -1;
    if (a.name > b.name) return 1;
    return 0;
  }
  // else check for null
  if (a.id === null) return 1;
  if (b.id === null) return -1;
  // if both are different return the difference to sort based on that
  return a.id - b.id
});

console.log(friends);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用算术计算来确定位置:

逻辑:

  • 对于ID,因为我们只需查看可用性,请将其设置为1-1并进行比较。
  • 比较名称并相应地对其进行排序,然后添加ID比较值。
  • 根据优先级设置值。因此,所有具有ID的成员都需要首先显示,因此具有更高的价值。

var data=[{id:1122,name:"Adrianna Budzinski"},{id:3785,name:"Amy Divine"},{id:1555,name:"Gale Purdue"},{id:1920,name:"Rex Feng"},{id:2010,name:"Samella Vizcaino"},{id:null,name:"Bethanie Weaver"},{id:null,name:"Celesta Gullo"},{id:null,name:"Darrick Fort"},{id:null,name:"Edmundo Boulanger"},{id:null,name:"Freddie Lanclos"},{id:null,name:"Gregory Lickteig"},{id:null,name:"Gwendolyn Cuadra"},{id:null,name:"Krystal Brosnahan"},{id:null,name:"Lahoma Pagani"},{id:null,name:"Senaida Risk"},{id:null,name:"Valarie Lopes"}];

data.sort(function(a,b){
  var _id1 = a.id? 1: -1;
  var _id2 = b.id? 1: -1;
  var rank = _id1 >_id2 ? -10: _id1< _id2 ? 10 : 0
  var v = a.name > b.name? 1: a.name < b.name? -1: 0;
  return rank + v;
});

document.getElementById("result").innerHTML = JSON.stringify(data,0,4)
<pre id="result"></pre>