在数组中分组子数组

Posted

技术标签:

【中文标题】在数组中分组子数组【英文标题】:Grouping Subarrays in Arrays 【发布时间】:2020-12-14 22:38:30 【问题描述】:

我正在思考以下逻辑,但我仍然缺少一些东西。

给定一个像const testArr = ["F", "F", "C", "C", "F", "C", "F"] 这样的数组。

结果数组应类似于["F", "F", ["C", "C"], "F", ["C"], "F"]

我到现在为止的代码是这样的:

const grouping = (arr) => 
  const result = [];
  arr.forEach((item, index) => 
    if (item === "C") 
      const subArr = new Array();
      subArr.push(item);
      if (arr[index + 1] !== "C") 
        result.push(subArr);
      
     else 
      result.push(item);
    
  );
  return result;
;

console.log(grouping(testArr));

这会打印当前的结果:

["F", "F", ["C"], "F", ["C"], "F"]

感谢您的提示 :-)

【问题讨论】:

【参考方案1】:

您可以使用带有临时索引的 while 循环来实现您的预​​期结果

以下是您当前解决方案的小修改(更改为 for 循环并使用 while 进行条件检查)

const testArr = ["F", "F", "C", "C", "F", "C", "F"]

const grouping = (arr) => 
  const result = []
  for (let index = 0; index < arr.length; index++) 
    if (arr[index] === "C") 
      const subArr = [arr[index]]
      let tempIndex = index + 1
      while (arr[tempIndex] === "C") 
        subArr.push(arr[tempIndex])
        index = tempIndex
        tempIndex++
      
      result.push(subArr)
     else 
      result.push(arr[index])
    
  

  return result


console.log(grouping(testArr))

【讨论】:

【参考方案2】:

我想我会这样做,见 cmets:

const grouping = arr => 
    const result = [];
    let currentSub = null;
    for (const value of arr) 
        // Is it the special value?
        if (value === "C") 
            // Yes, do we have an active array?
            if (!currentSub) 
                // No, create one and push it
                currentSub = [];
                result.push(currentSub);
            
            // Add to the active array
            currentSub.push(value)
         else 
            // Not special, forget active array and push
            currentSub = null;
            result.push(value);
        
    
    return result;
;

现场示例:

const testArr = ["F", "F", "C", "C", "F", "C", "F"]

const grouping = arr => 
    const result = [];
    let currentSub = null;
    for (const value of arr) 
        // Is it the special value?
        if (value === "C") 
            // Yes, do we have an active array?
            if (!currentSub) 
                // No, create one and push it
                currentSub = [];
                result.push(currentSub);
            
            // Add to the active array
            currentSub.push(value)
         else 
            // Not special, forget active array and push
            currentSub = null;
            result.push(value);
        
    
    return result;
;

console.log(grouping(testArr));
.as-console-wrapper 
    max-height: 100% !important;

如果您更喜欢forEach 而不是for-of,它几乎是相同的:

const testArr = ["F", "F", "C", "C", "F", "C", "F"]

const grouping = arr => 
    const result = [];
    let currentSub = null;
    arr.forEach(value => 
        // Is it the special value?
        if (value === "C") 
            // Yes, do we have an active array?
            if (!currentSub) 
                // No, create one and push it
                currentSub = [];
                result.push(currentSub);
            
            // Add to the active array
            currentSub.push(value)
         else 
            // Not special, forget active array and push
            currentSub = null;
            result.push(value);
        
    );
    return result;
;

console.log(grouping(testArr));
.as-console-wrapper 
    max-height: 100% !important;

旁注:一般情况下,请避免使用new Array()。要创建一个空白数组,只需使用[]。要创建包含条目的数组,请使用 [value1, value2] 等。您可以使用 new Array(x)(或仅使用 Array(x))创建长度为 xsparse 数组,但这通常只有用当您要在其上使用fill 以在每个条目中填充相同的值时。

【讨论】:

【参考方案3】:

我会使用一个临时数组来存储“特殊”值,并且我会在遇到不同值时重置它。

const grouping = (arr) => 
  const result = []
  let tempC = []
  
  arr.forEach(letter => 
    if (letter === 'C') 
       tempC.push('C')         // Append the special letter to its temp array
     else 
       if (tempC.length > 0) 
         result.push(tempC)    // If the previus iteration had a 'C', push the array in result
       
       tempC = []              // Reset the tempC collector
       result.push(letter)     // Add the 'not special' letter to the result
    
  )
  return result

【讨论】:

【参考方案4】:

const testArr = ["F", "F", "C", "C", "F", "C", "F"];
const result = testArr.reduce((acc, val) => 
    if (val === "C") 
        Array.isArray(acc[acc.length - 1]) ? acc[acc.length - 1].push(val) : acc.push([val]);
     else 
        acc.push(val);
    

    return acc;
, []);

console.log(result);

【讨论】:

【参考方案5】:

这是一种使用 DRY 函数 Array.prototype.reduce 的方法。

const testArr = ["F", "F", "C", "C", "F", "C", "F"];
const result = testArr.reduce((a, e) => 
  if (e === a.target) (a.current || (a.current = [])).push(e);
  else 
    if (a.current) a.result.push(a.current), a.current = undefined;   
    a.result.push(e);
  
  
  return a;
, result: [], current: undefined, target: "C");

console.log(result);
.as-console-wrapper  max-height: 100% !important; top: 0; 

【讨论】:

【参考方案6】:

void groupElements(int arr[], int n) 
 
    // Initialize all elements as not visited 
    bool *visited = new bool[n]; 
    for (int i=0; i<n; i++) 
        visited[i] = false; 
  
    // Traverse all elements 
    for (int i=0; i<n; i++) 
     
        // Check if this is first occurrence 
        if (!visited[i]) 
         
            // If yes, print it and all subsequent occurrences 
            cout << arr[i] << " "; 
            for (int j=i+1; j<n; j++) 
             
                if (arr[i] == arr[j]) 
                 
                    cout << arr[i] << " "; 
                    visited[j] = true; 
                 
             
         
     
  
    delete [] visited;   
 

【讨论】:

我不确定 C++ 如何适合 OP javascript 代码;)

以上是关于在数组中分组子数组的主要内容,如果未能解决你的问题,请参考以下文章

按子数组值对数组进行分组

如何在数组的 mongodb 的子字段中进行聚合和分组?

2607. 使子数组元素和相等

POJ 3415 Common Substrings(长度不小于K的公共子串的个数+后缀数组+height数组分组思想+单调栈)

POJ - 1743 后缀数组 height分组

如何对数组中的连续整数进行分组?