我需要使用underscore.js过滤我的数据结构以生成图表。
var data = [
["Name", "Class", "Rollno", "Subject"],
["Anil", "10", "112121212", "BAS"],
["Sunil", "10", "112121212", "BAS"]
];
因此,如果在这种情况下我将Name
作为键传递,则过滤器应仅删除第一列。此外,我想传入一个列名列表,以便从我的数据结构中删除多个列。
任何帮助都会非常感激。
答案 0 :(得分:0)
Underscore提供"有用的函数式编程助手"并且是一个很棒的库,可以以更实用的方式编写JavaScript。某些方法可能已包含在现代JavaScript中。
该代码使用以下下划线方法:filter,each,map和contains
以下适用于单个列。
// Find the column index within the first row of the dataset
// using the given column name. This index will later be used in
// the filter.
//
// Take care, indexOf will return -1 if the column name was not found
// which would be a invalid index
var index = data[0].indexOf("Name");
// Generate a new dataset by collecting the filtered rows
// The input to the mapping function is each row.
var withoutColumn = _.map(data, function (row) {
// Apply a filter on each element in the row;
// The second parameter to the filter function is the current index
// of the element within the row.
return _.filter(row, function (r, idx) {
// Return true if the current index idx does not match the
// preselected index. This effectively removes the selected
// column.
return idx !== index;
});
});
现在让我们为许多列扩展它:
a)获取要删除的列的所有索引的列表。
b)在过滤器中采用测试方法来检查当前索引是否在先前找到的索引列表中。
function removeColumnsByName(data, columnNames) {
// Collect the index of each given column name in the array indexes
var indexes = [];
// Iterate over the column names
_.each(data[0], function(column, idx) {
// If the current column name is contained in the given column
// names store its index idx in indexes.
if (_.contains(columnNames, column)) {
indexes.push(idx);
}
});
// Again collect the filtered rows using a different filter function
return _.map(data, function (row) {
return _.filter(row, function (r, idx) {
// Modified test: return true if the current index idx is not
// contained in the list of indexes
return ! _.contains(indexes, idx);
});
});
}
console.log (removeColumnsByName(data, ["Name", "Subject"]));
要按列名删除行,可以使用以下方法:
function filterByName (data, name) {
return _.filter(data, function (entry) {
return entry[0] !== name;
});
}
答案 1 :(得分:0)
如果我理解正确,你想要这样的输出? :
[
["Class","Rollno","Subject"],
[ "10", "112121212","BAS"],
[ "10", "112121212","BAS"]
]
尝试:
data.forEach(item => item.splice(0))
如果要对任何列执行此操作,请使用:
data.forEach(item => item.splice(n)) // n is column index (zero based)