[英]How to return values after boolean in multidemensional array?
Im trying to filter a multidimensional array to return only the indexes after a boolean in this array.我试图过滤多维数组以仅返回此数组中 boolean 之后的索引。
The first key in this array needs to stay in the array like "Tafelblad model" and "Uitstraling" And the optional values after the booleans该数组中的第一个键需要像“Tafeblad model”和“Uitstraling”一样留在数组中,以及布尔值后面的可选值
["Tafelblad model", true, "Rechthoekig", "Vierkant", "Ovaal / Rond / Overig"],
["Uitstraling", "Licht robuust", "Midden robuust", true, "Zwaar robuust", "Weinig", "Midden (standaard)", true, "Veel oneffenheden en scheuren"]`
The new array would be like新数组就像
["Tafelblad model", "Rechthoekig"],
["Uitstraling", "Zwaar robuust", "Veel oneffenheden en scheuren"]`
You can close over a flag that you set to keep the next entry you see:您可以关闭您设置的标志以保留您看到的下一个条目:
let flag = true; // We want the first one
const newArray = array.filter(entry => {
const keep = flag;
flag = typeof entry === "boolean";
return keep;
});
Live Example:现场示例:
function example(array) { let flag = true; // We want the first one const newArray = array.filter(entry => { const keep = flag; flag = typeof entry === "boolean"; return keep; }); console.log(newArray); } example(["Tafelblad model", true, "Rechthoekig", "Vierkant", "Ovaal / Rond / Overig"]); example(["Uitstraling", "Licht robuust", "Midden robuust", true, "Zwaar robuust", "Weinig", "Midden (standaard)", true, "Veel oneffenheden en scheuren"]);
You can use the .filter(..)
function for that, here is an example:您可以为此使用
.filter(..)
function,这是一个示例:
let arr1 = ["Tafelblad model", true, "Rechthoekig", "Vierkant", "Ovaal / Rond / Overig"]; let arr2 = ["Uitstraling", "Licht robuust", "Midden robuust", true, "Zwaar robuust", "Weinig", "Midden (standaard)", true, "Veel oneffenheden en scheuren"]; const filterFn = (value, index, arr) => { return index === 0 || arr[index - 1] === true; }; arr1 = arr1.filter(filterFn); arr2 = arr2.filter(filterFn); console.log(arr1); console.log(arr2);
The callback function passed to .filter(..)
receives the value at the current iteration, the current iteration's index and the original array as parameters.传递给
.filter(..)
的回调 function 接收当前迭代的值、当前迭代的索引和原始数组作为参数。 The conditions in the filterFn
function check if the iteration's index is 0
(the value is the first value in the array) or the previous item is strict equal to true
filterFn
function 中的条件检查迭代的索引是否为0
(该值是数组中的第一个值)或前一项严格等于true
Using map()
and filter()
使用
map()
和filter()
let arrays = [ ["Tafelblad model", true, "Rechthoekig", "Vierkant", "Ovaal / Rond / Overig"], ["Uitstraling", "Licht robuust", "Midden robuust", true, "Zwaar robuust", "Weinig", "Midden (standaard)", true, "Veel oneffenheden en scheuren"] ] let result = arrays.map(arr => { return arr.filter((v, i) => typeof arr[i - 1] === "boolean" || i == 0); }) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.