如何将数组公共元素对齐至同一索引位置并补全null值
Solution Approach
The core idea here is to align all occurrences of the same string across columns by assigning each unique string a fixed row position. Here's a step-by-step breakdown:
- Gather all unique strings: Collect every distinct string from all input columns.
- Assign row positions: Sort these unique strings (lexicographical order works perfectly for your example) and map each string to a row index based on its sorted position.
- Build aligned columns: For each input column, create an array where each string is placed in its assigned row position, filling gaps with
null. Finally, trim any trailingnulls to match your example's output format.
Example Code (JavaScript)
// Input array from your example const input = [ ['a', 'b', 'c'], ['b', 'c', 'd'], ['a', 'd', 'b'] ]; // Step 1: Collect and sort all unique strings const uniqueStrings = [...new Set(input.flat())].sort(); // Step 2: Create a mapping from string to its row index const stringToRow = uniqueStrings.reduce((map, str, index) => { map[str] = index; return map; }, {}); // Step3: Process each input column to create aligned output const output = input.map(column => { // Initialize array with nulls for each unique string const alignedColumn = Array(uniqueStrings.length).fill(null); // Place each string in its assigned row column.forEach(str => { alignedColumn[stringToRow[str]] = str; }); // Trim trailing nulls (matches your example's format) while (alignedColumn.length > 0 && alignedColumn.at(-1) === null) { alignedColumn.pop(); } return alignedColumn; }); console.log(output); // Output: [ ['a','b','c'], [null,'b','c','d'], ['a','b',null,'d'] ]
Key Notes
- Sorting Order: The example uses lex order, but you can adjust this (e.g., based on the first occurrence of strings across columns) by modifying how you collect
uniqueStrings. For first occurrence order:const uniqueStrings = []; input.flat().forEach(str => { if (!uniqueStrings.includes(str)) uniqueStrings.push(str); }); - Handling Duplicates: If a column has duplicate strings, this approach will overwrite the same row position (which is fine since the string is identical).
- Trailing Nulls: The trimming step is optional but matches your example where shorter columns don't include nulls for rows beyond their last string.
内容的提问来源于stack exchange,提问作者Chris White
相关产品推荐
相关产品推荐

