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

如何仅通过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

  1. Initialize the original array with your given values.
  2. Create an empty array to store the unique elements we find.
  3. Loop through each element in the original array.
  4. For each element, check if it's already present in our unique array using another nested for loop.
  5. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 20:17:30