数组元素全倒排列并去重
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:
-
slice()for Non-Destructive Reversal: Thearr.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. -
Setfor Efficient Deduplication: Using aSetto track seen elements provides efficient deduplication.Set.has()has an average time complexity of O(1), making the overall deduplication process faster than usingindexOfor other array-based methods. -
Concise Version: The
reverseAndDedupConcisefunction demonstrates a more concise way to achieve the same result using the spread operator (...) andSet. -
Legacy Browser Support (Optional): The
reverseAndDedupLegacyfunction shows how to accomplish the same task without usingSet, 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.
浙公网安备 33010602011771号