如何仅通过for循环遍历数组并返回去重后的原始数据
Solution to Remove Duplicates Using Only For Loops
Got it, let's solve this step by step. The goal is to take your array and extract unique values using nothing but for loops. Here's how you can do it:
Step-by-Step Explanation
- Initialize the original array with your given values.
- Create an empty array to store the unique elements we find.
- Loop through each element in the original array.
- For each element, check if it's already present in our unique array using another nested
forloop. - If it's not present, add it to the unique array.
Working Code
// Your original array const originalArray = [2019, 2019, 2020, 2019, 2016, 2016, 2016, 2019, 2019, 2019, 2019]; // Empty array to hold unique values const uniqueArray = []; // Outer loop: iterate through every element in the original array for (let i = 0; i < originalArray.length; i++) { let isDuplicate = false; // Inner loop: check if current element is already in uniqueArray for (let j = 0; j < uniqueArray.length; j++) { if (originalArray[i] === uniqueArray[j]) { isDuplicate = true; break; // Exit inner loop early once we find a match } } // If not a duplicate, add to uniqueArray if (!isDuplicate) { uniqueArray.push(originalArray[i]); } } console.log(uniqueArray); // Output: [2019, 2020, 2016]
Notes on the Result Order
The code above gives unique values in the order of their first occurrence in the original array (2019 first, then 2020, then 2016). If you specifically need the result [2019, 2016, 2020], you can adjust the logic to prioritize adding 2016 before 2020 by checking for those specific values during the loop, or reorder the unique array after collecting the values. The core duplicate-removal logic remains solid regardless of the final order you need.
内容的提问来源于stack exchange,提问作者Aishwarya Kathavarayan
相关产品推荐
相关产品推荐

