You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数组公共元素对齐至同一索引位置并补全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:

  1. Gather all unique strings: Collect every distinct string from all input columns.
  2. 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.
  3. 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 trailing nulls 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:37:32