2016-03-06 88 views
0

我有这些2个数组:排序/过滤从2个阵列

var masterArray = [ 
     {'id' : '1', 'title' : 'Title 1'}, 
     {'id' : '2', 'title' : 'Title 2'}, 
     {'id' : '3', 'title' : 'Title 3'}, 
     {'id' : '4', 'title' : 'Title 4'}, 
     {'id' : '5', 'title' : 'Title 5'}, 
     {'id' : '6', 'title' : 'Title 6'}, 
     {'id' : '7', 'title' : 'Title 7'} 
    ]; 

var sortFilterInfo = [ 
    {'id' : '6', 'sortOrder' : 1}, 
    {'id' : '2', 'sortOrder' : 2}, 
    {'id' : '7', 'sortOrder' : 3} 
] 

有了这个信息我需要一种阵列,其给我此排序过滤数组:(我只使用本机DOM Array方法(ES6)(图/过滤/排序)和了jQuery,lodash等

var resultArray = [ 
    {'id' : '6', 'title' : 'Title 6'}, 
    {'id' : '2', 'title' : 'Title 2'}, 
    {'id' : '7', 'title' : 'Title 7'} 
] 

感谢

+0

所以不使用任何外部JavaScript库? –

+0

好吧,这是关键。但只要它不jQuery的我不介意带来另一个JS UTIL LIB – 29er

+0

是sortFilterInfo静态值,还是会在某个时间点是动态的? –

回答

3

是否该作品(编辑:!?评论,如果你要我给它做了什么)

// Create arrays 
var masterArray = [ 
    {'id' : '1', 'title' : 'Title 1'}, 
    {'id' : '2', 'title' : 'Title 2'}, 
    {'id' : '3', 'title' : 'Title 3'}, 
    {'id' : '4', 'title' : 'Title 4'}, 
    {'id' : '5', 'title' : 'Title 5'}, 
    {'id' : '6', 'title' : 'Title 6'}, 
    {'id' : '7', 'title' : 'Title 7'} 
]; 

var sortFilterInfo = [ 
    {'id' : '6', 'sortOrder' : 1}, 
    {'id' : '2', 'sortOrder' : 2}, 
    {'id' : '7', 'sortOrder' : 3} 
] 

var resultArray = new Array(); 

// Sort arrays 
masterArray.sort(function(a, b){return parseInt(a.id)-parseInt(b.id)}); 
sortFilterInfo.sort(function(a, b){return a.sortOrder-b.sortOrder}); 

// Push to array the id of the filter... 
for (var i in sortFilterInfo) { 
    resultArray.push(masterArray[parseInt(sortFilterInfo[i].id)-1]); 
} 

// console.log(resultArray); 
// 
// resultArray = [ 
//  {'id' : '6', 'title' : 'Title 6'}, 
//  {'id' : '2', 'title' : 'Title 2'}, 
//  {'id' : '7', 'title' : 'Title 7'} 
// ] 
+0

哇非常酷,就像一个魅力。谢谢! – 29er

+0

谢谢!我很开心做这个! –

+0

安德鲁你看起来像你12.小天才:)再次感谢 – 29er

1

你刚才去通过sortFilterInfo数组,然后摘去从主阵列中的项目。

下面是一个例子:

function myFunc(master, sortOrder) { 
    var result = []; 

    // Sort sortOrder so it is ordered correctly 
    // The array is cloned so it does not affect 
    // the original array 
    var order = sortOrder.concat().sort(function (a, b) { 
     return a.sortOrder - b.sortOrder; 
    }); 
    // Function to find an item in the master array 
    var find = function (value) { 
     var result = -1; 
     master.some(function (item, index) { 
      if (item.id == value) { 
       result = index; 
       return true; 
      } 
     }); 
     return result; 
    }; 
    // Go through the orderings and pick the items 
    // from the master array 
    order.forEach(function (item) { 
     var index = find(item.id); 
     if (index !== -1) { 
      result.push(master[index]); 
     } 
    }); 
    return result; 
} 
var result = myFunc(masterArray, sortFilterInfo); 
+0

这个工程太棒了!特别是当主数组ID不是数字时,而是随机文本。 – 29er