Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Chuyển mảng 2D thành mảng thưa (sparse array) của mảng trong JavaScript


Giả sử chúng ta có mảng 2-D như sau:

const arr = [ 
    [3, 1], 
    [2, 12], 
    [3, 3] 
];

Cần viết hàm nhận mảng như vậy. Hàm sẽ tạo mảng 2-D mới chứa tất cả phần tử khởi tạo là undefined trừ các chỉ số có trong mảng đầu vào.

Với mảng đầu vào:

output[3][1] = 1; output[2][12] = 1; output[3][3] = 1;

Các phần tử còn lại khởi tạo là undefined. Đầu ra cuối cùng:

const output = [ 
    undefined, 
    undefined, 
    [ 
        undefined, 
        undefined, 
        undefined, 
        undefined, 
        undefined, 
        undefined, 
        undefined, 
        undefined, 
        undefined, 
        undefined, 
        undefined, 
        1 
    ], 
    [ 
        undefined, 
        1, 
        undefined, 
        1 
    ] 
];

Ví dụ

Mã thực hiện như sau:

const arr = [ 
    [3, 1], 
    [2, 12], 
    [3, 3] 
]; 
const map2D = (arr = []) => { 
    const res = []; 
    arr.forEach(el => { 
        res[el[0]] = res[el[0]] || []; 
        res[el[0]][el[1]] = 1; 
    }); 
    return res; 
}; 
console.log(map2D(arr));

Kết quả

Kết quả trong console sẽ là:

[ 
    <2 empty items>, 
    [ <12 empty items>, 1 ], 
    [ <1 empty item>, 1, <1 empty item>, 1 ] 
]