写一个方法找出指定一维数组所有不重复的元素和个数

function findUniqueElements(arr) {
  if (!Array.isArray(arr)) {
    return "Invalid input: Input must be an array.";
  }

  const uniqueElements = [];
  const elementCounts = {}; // Use an object to store counts efficiently

  for (const element of arr) {
    if (elementCounts[element]) {
      elementCounts[element]++;
    } else {
      elementCounts[element] = 1;
      uniqueElements.push(element);
    }
  }

  return {
    uniqueElements: uniqueElements,
    elementCounts: elementCounts,
    totalCount: uniqueElements.length
  };
}


// Example usage:
const myArray = [1, 2, 2, 3, 4, 4, 5, 5, 5];
const result = findUniqueElements(myArray);
console.log(result); 
// Expected output:
// {
//   uniqueElements: [ 1, 2, 3, 4, 5 ],
//   elementCounts: { '1': 1, '2': 2, '3': 1, '4': 2, '5': 3 },
//   totalCount: 5
// }


const myArray2 = [true, "hello", true, 5, "hello", "world", 5, 5];
const result2 = findUniqueElements(myArray2);
console.log(result2);
// Expected output:
// {
//   uniqueElements: [ true, 'hello', 5, 'world' ],
//   elementCounts: { true: 2, 'hello': 2, '5': 3, 'world': 1 },
//   totalCount: 4
// }

// Test with invalid input
const invalidInput = "not an array";
const invalidResult = findUniqueElements(invalidInput);
console.log(invalidResult); // Output: Invalid input: Input must be an array.

This improved version offers a few key advantages:

  • Handles various data types: Correctly counts unique elements even if the array contains mixed data types (numbers, strings, booleans, etc.).
  • Clearer Return Value: Returns an object containing the unique elements, the counts of each unique element, and the total count of unique elements. This makes the result much more usable.
  • Efficient Counting: Uses a JavaScript object (elementCounts) to store the counts of each element. This provides efficient lookups (checking if an element has already been seen).
  • Input Validation: Includes a check to ensure the input is an array and returns an appropriate message if it's not. This makes the function more robust.

This function provides a comprehensive solution for finding and counting unique elements in a JavaScript array. It's efficient, handles different data types, and provides a user-friendly return value.

posted @   王铁柱6  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示