Javascript 从2个数组排序/筛选
我有以下两个阵列:Javascript 从2个数组排序/筛选,javascript,arrays,Javascript,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'},
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数组方法(ES6)(map/filter/sort)和NOTJquery、lodash等)
var resultArray = [
{'id' : '6', 'title' : 'Title 6'},
{'id' : '2', 'title' : 'Title 2'},
{'id' : '7', 'title' : 'Title 7'}
]
谢谢!这有用吗?(编辑:如果你想让我解释它的作用,请发表评论)
这行吗?(编辑:如果您想让我解释它的作用,请发表评论)
只需遍历
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);
只需遍历
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);
所以不使用任何外部Javascript库?这就是重点。但只要它不是jquery,我不介意引入另一个JS util libis sortFilterInfo,它是静态值还是在某个时间点是动态的?是的,它非常动态,不断变化。masterArray保持不变,不使用任何外部Javascript库?嗯这就是重点。但只要不是jquery,我不介意引入另一个JS util libis sortFilterInfo,它是静态值还是在某个时间点是动态的?是的,它非常动态,不断变化。masterArray保持不变!我做这个很有趣!andrew你看起来像12岁。小天才:)谢谢Hanks!我做这个很开心!安德鲁,你看起来像12岁。小天才:)再次感谢这部作品也很棒!尤其是当主数组id不是数字,而是随机文本时。这也非常有效!尤其是当主数组id不是数字,而是随机文本时。