简体   繁体   中英

Javascript convert multidimentional array to indexes

My script working just fine but I don't know why there is an inner voice inside my head that tells me that there must be an 'Inside the box' solution instead of writing a function or a much simpler way to get what I want.

All I want is to get the array indexes (not keys) instead of the values.

Here is my simple code:

<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8>
<title>&nbsp;</title>
<style></style>
</head>
<body>

<script>

function arrayIndexes(arrConvert)
{

    var newArr=[];

    for(y in arrConvert)
    {
        newArr[y]=[];
        for(x in arrConvert[y])
        {
            newArr[y][x]=parseInt(x);
        }
    }
    
    return newArr;

}

var menu=
[
    ['Spaghetti','Pizza','Lazanya'],
    ['Vinaigrette','Mushroom','Ketchup'],
    ['Bon Appétit'],
    ['Steve Vai','Joe Satriani','Hezi Gangina','Nuno Bettencourt']
];

console.table(arrayIndexes(menu));

</script>
</body>

Is there any magic trick to replace the function with 'inTheBox' javascript solution or some other smoother way? I want to make it as clean as possible.

You can use array map method, spread syntax and keys method to do your job. Traverse the array of arrays and get all the indexes and map it.

 const menu = [ ['Spaghetti', 'Pizza', 'Lazanya'], ['Vinaigrette', 'Mushroom', 'Ketchup'], ['Bon Appétit'], ['Steve Vai', 'Joe Satriani', 'Hezi Gangina', 'Nuno Bettencourt'], ]; const arrayIndexes = (arrConvert) => arrConvert.map((x) => [...x.keys()]); console.log(arrayIndexes(menu));

 const menu = [ ["Spaghetti", "Pizza", "Lazanya"], ["Vinaigrette", "Mushroom", "Ketchup"], ["Bon Appétit"], ["Steve Vai", "Joe Satriani", "Hezi Gangina", "Nuno Bettencourt"], ]; const sol = menu.map(arr => [arr.map((_, i) => i)]).flat(); //console.table(sol); console.log(sol);

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