数组元素全倒排列并去重

function reverseAndDedup(arr) {
  // Reverse the array
  const reversedArr = arr.slice().reverse();

  // Deduplicate the reversed array
  const uniqueArr = [];
  const seen = new Set();

  for (const element of reversedArr) {
    if (!seen.has(element)) {
      uniqueArr.push(element);
      seen.add(element);
    }
  }

  return uniqueArr;
}



// Example usage:
const originalArray = [1, 2, 2, 3, 4, 4, 5, 1];
const reversedUniqueArray = reverseAndDedup(originalArray);
console.log(reversedUniqueArray); // Output: [1, 5, 4, 3, 2]


//More concise version using Set and spread operator
function reverseAndDedupConcise(arr) {
  return [...new Set(arr.slice().reverse())];
}

const originalArray2 = [1, 2, 2, 3, 4, 4, 5, 1];
const reversedUniqueArray2 = reverseAndDedupConcise(originalArray2);
console.log(reversedUniqueArray2); // Output: [1, 5, 4, 3, 2]



//  If you need to support older browsers that don't have Set, you can use a plain object to achieve the same result:

function reverseAndDedupLegacy(arr) {
  const reversedArr = arr.slice().reverse();
  const uniqueArr = [];
  const seen = {};

  for (let i = 0; i < reversedArr.length; i++) {
    const element = reversedArr[i];
    if (!seen[element]) { // Check if the element is already in 'seen'
      uniqueArr.push(element);
      seen[element] = true; // Mark the element as seen
    }
  }

  return uniqueArr;
}

const originalArray3 = [1, 2, 2, 3, 4, 4, 5, 1];
const reversedUniqueArray3 = reverseAndDedupLegacy(originalArray3);
console.log(reversedUniqueArray3); // Output: [1, 5, 4, 3, 2]

Explanation and Key Improvements:

  1. slice() for Non-Destructive Reversal: The arr.slice().reverse() method creates a copy of the original array before reversing it. This is crucial to avoid modifying the original array, which is generally good practice.

  2. Set for Efficient Deduplication: Using a Set to track seen elements provides efficient deduplication. Set.has() has an average time complexity of O(1), making the overall deduplication process faster than using indexOf or other array-based methods.

  3. Concise Version: The reverseAndDedupConcise function demonstrates a more concise way to achieve the same result using the spread operator (...) and Set.

  4. Legacy Browser Support (Optional): The reverseAndDedupLegacy function shows how to accomplish the same task without using Set, which is important for compatibility with older browsers.

Choosing the right version depends on your target browser compatibility and coding style preferences. The Set-based versions are generally preferred for their conciseness and efficiency. If you need to support very old browsers, the legacy version is a good fallback.

posted @ 2024-12-11 09:45  王铁柱6  阅读(11)  评论(0)    收藏  举报