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

实现数组重复元素分组与字符串独立分组的函数开发问题

Solution for Grouping Duplicates and Separating Strings in Arrays

Hey there! Let's fix up your code and build the function you need. First, let's break down what went wrong with your initial attempts, then walk through a working solution.

What's Off With Your Current Code

  • First attempt: The map callback uses num[i] which doesn't make sense (you don't have an i variable defined here), and your reduce usage doesn't actually track duplicates. Plus, recursively calling sortArray() would cause an infinite loop.
  • Second attempt: acc.findIndex(num) is invalid—findIndex needs a callback function (like acc.findIndex(item => item === num)), and your logic doesn't handle grouping duplicates at all, just tries to concatenate elements.

Working Function for Pure Numeric Arrays

Let's start with the pure numeric case you provided. This function will group elements that appear multiple times into subarrays, while keeping single-occurrence elements as standalone values:

const roughArray = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];

function groupDuplicates(arr) {
  // Step 1: Track unique elements and their full groups
  const uniqueGroups = arr.reduce((map, item) => {
    if (!map.has(item)) {
      // Collect all instances of the current item
      map.set(item, arr.filter(el => el === item));
    }
    return map;
  }, new Map());

  // Step 2: Convert groups to final format (array if multiple, single value if one)
  return Array.from(uniqueGroups.values()).map(group => 
    group.length > 1 ? group : group[0]
  );
}

console.log(groupDuplicates(roughArray));
// Output: [[1,1,1,1],[2,2,2],4,591,392,391,5,10,[20,20]]

Handling Mixed Arrays (Numbers + Strings)

For arrays that include strings, we'll first separate numeric and string elements, process the numbers as before, and group all strings into a dedicated subarray (or group string duplicates too—adjust based on your needs):

const mixedArray = [1, 1, 2, "2", "3", "3"];

function groupDuplicatesWithStrings(arr) {
  // Split array into numbers and strings
  const numbers = arr.filter(el => typeof el === 'number');
  const strings = arr.filter(el => typeof el === 'string');

  // Process numbers (same logic as pure numeric function)
  const numberGroups = numbers.reduce((map, item) => {
    if (!map.has(item)) {
      map.set(item, numbers.filter(el => el === item));
    }
    return map;
  }, new Map());
  const processedNumbers = Array.from(numberGroups.values()).map(group => 
    group.length > 1 ? group : group[0]
  );

  // Process strings: either group all together, or group their duplicates
  const processedStrings = strings.length > 0 
    ? [strings] // All strings in one subarray (matches your example)
    : [];
    // If you want to group string duplicates too, use this instead:
    // strings.reduce((map, item) => {
    //   if (!map.has(item)) map.set(item, strings.filter(el => el === item));
    //   return map;
    // }, new Map()).values().map(g => g.length>1 ? g : g[0]);

  // Combine results
  return [...processedNumbers, ...processedStrings];
}

console.log(groupDuplicatesWithStrings(mixedArray));
// Output: [[1,1],2,["2","3","3"]]
// If using duplicate grouping for strings: [[1,1],2,["2"],["3","3"]]

How It Works

  1. Tracking Groups: We use a Map to avoid processing the same element multiple times. For each unique element, we collect all its instances from the original array.
  2. Formatting Results: For each group, if it has more than one element, we keep it as a subarray; otherwise, we use the single element directly.
  3. Mixed Type Handling: We split the array by type first, process numbers separately, then add the string group(s) to the final result.

内容的提问来源于stack exchange,提问作者saas_joel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:48:44