2016-02-25 73 views
4

我有對象的這樣與具有點屬性對象的排序陣列分離數

var arr = [{ 
    "id": "1", 
    "Title": "Object1", 
    "SectionId": "1.2.1" 
}, { 
    "id": "2", 
    "Title": "Object2", 
    "SectionId": "1.1.2" 
}, { 
    "id": "3", 
    "Title": "Object3", 
    "SectionId": "1.0.1" 
}, { 
    "id": "4", 
    "Title": "Object4", 
    "SectionId": "1" 
}]; 

sectionId具有分隔多個點陣列。如何根據sectionId屬性按升序或降序排列數組?

+1

([通過在JavaScript字符串屬性值排序對象數組]的可能的複製http://stackoverflow.com/questions/1129216/按照字符串排序的屬性值) – A1rPun

+0

看看這個https://jsfiddle.net/62cuna7w/2/ – Ionut

回答

2

靈感來自Sorting with map

function customSort(d, order) { 
 
    var sort = { 
 
      asc: function (a, b) { 
 
       var l = 0, m = Math.min(a.value.length, b.value.length); 
 
       while (l < m && a.value[l] === b.value[l]) { 
 
        l++; 
 
       } 
 
       return l === m ? a.value.length - b.value.length : a.value[l] - b.value[l]; 
 
      }, 
 
      desc: function (a, b) { 
 
       return sort.asc(b, a); 
 
      } 
 
     }, 
 

 
     // temporary array holds objects with position and sort-value 
 
     mapped = d.map(function (el, i) { 
 
      return { index: i, value: el.SectionId.split('.').map(Number) }; 
 
     }); 
 

 
    // sorting the mapped array containing the reduced values 
 
    mapped.sort(sort[order] || sort.asc); 
 

 
    // container for the resulting order 
 
    return mapped.map(function (el) { 
 
     return d[el.index]; 
 
    }); 
 
} 
 

 
var arr = [{ "id": "1", "Title": "Object1", "SectionId": "1.2.1" }, { "id": "2", "Title": "Object2", "SectionId": "1.1.2" }, { "id": "3", "Title": "Object3", "SectionId": "1.0.1" }, { "id": "4", "Title": "Object4", "SectionId": "1.1.10" }, { "id": "5", "Title": "Object5", "SectionId": "1" }]; 
 

 
document.write('<pre>sorted array asc ' + JSON.stringify(customSort(arr), 0, 4) + '</pre>'); 
 
document.write('<pre>sorted array desc ' + JSON.stringify(customSort(arr, 'desc'), 0, 4) + '</pre>'); 
 
document.write('<pre>original array ' + JSON.stringify(arr, 0, 4) + '</pre>');

1
var sort = function(isAsc) { 
    return function(a, b) { 
     var x = a.SectionId.split('.').map(Number) 
     var y = b.SectionId.split('.').map(Number) 
     for (var i = 0; i < 3; i++) { 
      if (x[i] > y[i]) return isAsc ? 1 : -1; 
      if (x[i] < y[i]) return isAsc ? -1 : 1; 
      if (!isNaN(x[i]) && isNaN(y[i])) return isAsc ? 1 : -1; 
      if (isNaN(x[i]) && !isNaN(y[i])) return isAsc ? -1 : 1; 
     } 
     return 0; 
    } 
} 

var acs = sort(true) 
var desc = sort() 

arr.sort(acs) 
arr.sort(desc) 
+0

它沒有發現問題,它排序'1.1.10 ''1.1.2'之前,因爲字符串co mparison。 –

+0

@NinaScholz是的,你是對的。我已經更新回答 – isvforall

+0

這很奇怪,不是嗎? –

相關問題