我上面有一张表格和一张 map ,其中包含与下面的表格行相关的标记。当用户在上面的 map 上选择项目时,它会突出显示匹配的行,然后将这些行移动到表格的顶部,但会按照用户的排序设置进行排序。
例如,如果您有此原始数据(未显示的数据):
[
{id: 1, name: 'Z'},
{id: 2, name: 'Y'},
{id: 3, name: 'X'},
{id: 4, name: 'W'}
]
然后用户在 map 上选择 id: 1
和 id: 3
并按 name
排序。数据变为:
[
{id: 3, name: 'X'}, // selected
{id: 1, name: 'Z'}, // selected
{id: 4, name: 'W'}, // not selected
{id: 2, name: 'Y'} // not selected
]
有些数据集有 10,000 多行,我担心当他们选择项目时,由于 2 个过滤器 + 连接,这会锁定太久。有没有一种方法可以一次完成此操作,或者只是一种方法可以防止浏览器在执行此操作时锁定?
var selectedRows = rows.filter(function (row) {
return selectedMarkerIds.indexOf(row.id) !== -1
});
var nonSelectedRows = rows.filter(function (row) {
return selectedMarkerIds.indexOf(row.id) == -1
});
var allRows = selectedRows.concat(nonSelectedRows);
myTable.updateRowSort(allRows);
最佳答案
尝试减少。在回调函数中,它检查该行是否被选中并将其推送到结果对象中的适当数组。您一次性执行此操作,然后在最后一步连接数组。
var result = rows.reduce((result, row) => {
selectedMarkerIds.indexOf(row.id) !== -1 ? result.selected.push(row) : result.notSelected.push(row);
return result;
}, {
selected: [],
notSelected: []
});
result.selected.concat(result.notSelected);
我也是 lodash 的忠实粉丝,下面是 lodash 的实现。我首先将数组传递给 chain 函数,该函数基本上将它包装在一个 lodash 包装器周围,从而实现 lodash 函数的链接。然后我通过我的 reduce 函数传递数组,类似于我上面对 Array.prototype.reduce
所做的,但是这次结果的初始值是一个包含两个数组的数组:第一个数组用于选定的行,而第二个用于未选定的行。然后我使用 _.flatten
来展平嵌套数组,所以现在我们有一个对象数组而不是数组数组。我调用 value 来打开 lodash 包装器并获得我的最终值,它是一个行数组。
/**
* in the reduce function, the initial value of the
* result is an array of two arrays.
* the first array is for selected items.
* the second array is for non-selected items.
*/
var newArray = _.chain(rows)
.reduce((result, row) => {
selectedMarkerIds.indexOf(row.id) !== -1 ? result[0].push(row) : result[1].push(row);
return result;
}, [ [], [] ])
.flatten()
.value();
关于javascript - 按优先选择排序的更高效的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34459470/