简体   繁体   中英

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.

The first key in this array needs to stay in the array like "Tafelblad model" and "Uitstraling" And the optional values after the booleans

["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:

 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. 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

Using map() and 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM