对具有键作为数字的对象数组进行排序

时间:2018-07-10 07:35:55

标签: javascript jquery angularjs

我有以下对象数组:

@echo off
set STARTDIR="J:\MYFOLDER"
set /p id=Enter Label Code, please use this format  E.G. AA-01:
echo %id%
for /f "delims=" %%a in ('dir /s /b "J:\MYFOLDER"') do echo %%a

if exist %id% in ('dir /s /b "J:\MYFOLDER"') (
echo File found, starting NicePrint.
/! set current folder where file was found
The file path is %~dp1
Start "" "C:\Program Files (x86)\EuroPlus\NiceLabel 6\bin\NicePrint.exe" "J:\MYFOLDER\%~dp1\%id%"
) else exit
pause

现在,在这里我想使用startoffset和endoffset参数以升序对它进行排序。 新创建的对象数组中的第一个应该是第一个。

为此,我使用了以下逻辑

   [    
  {
        html: "<span class="email">",
        startOffset: "109"
        type: "Email"
    },
    {
        html: "<span class="email">",
        endOffset: "139"
        type: "Email"
    },
    {
        html: "<span class="email">",
        startOffset: "149"
        type: "Email"
    },
    {
        html: "<span class="email">",
        startOffset: "155"
        type: "Email"
    },
     {
        html: "<span class="email">",
        endOffset: "160"
        type: "Email"
    },
    {
        html: "<span class="email">",
        startOffset: "0"
        type: "Email"
    },
    {
        html: "<span class="email">",
        endOffset: "15"
        type: "Email"
    },
]

现在,这里是排序,但是当起始偏移量为0时,它就没有以正确的方式进行排序。所以,有人可以建议我哪里出问题了吗?

2 个答案:

答案 0 :(得分:0)

我不确定我是否理解您的问题。 这对我有用:

var newJSON = [{
    html: "<span class=\"email\">",
    startOffset: "109",
    type: "email"
  },
  {
    html: "<span class=\"email\">",
    endOffset: "139",
    type: "email"
  },
  {
    html: "<span class=\"email\">",
    startOffset: "149",
    type: "email"
  },
  {
    html: "<span class=\"email\">",
    startOffset: "155",
    type: "email"
  },
  {
    html: "<span class=\"email\">",
    endOffset: "160",
    type: "email"
  },
  {
    html: "<span class=\"email\">",
    startOffset: "0",
    type: "email"
  },
  {
    html: "<span class=\"email\">",
    endOffset: "15",
    type: "email"
  },
]

console.log(newJSON.map(i => i.startOffset || i.endOffset))

newJSON.sort(function(a, b) {
  var aVal = a.startOffset != undefined ? parseInt(a.startOffset) : parseInt(a.endOffset);
  var bVal = b.startOffset != undefined ? parseInt(b.startOffset) : parseInt(b.endOffset);
  return aVal - bVal;
});

console.log(newJSON.map(i => i.startOffset || i.endOffset))

有以下几点:

["109", "139", "149", "155", "160", "0", "15"]
["0", "15", "109", "139", "149", "155", "160"]

关于, 文森特

答案 1 :(得分:0)

检查空值或未定义的值:

function isNullOrUndefined(k){ 
     return typeof(k) === 'undefined' || k === null;
}

var aVal = isNullOrUndefined(a.startOffset) ? a.startOffset : a.endOffset;
var bVal = isNullOrUndefined(b.startOffset) ? b.startOffset : b.endOffset;