Sobes.tech
Middle

There is an array of numbers, some of which are repeated. How to create a new array without repetitions, preserving the order of numbers? How to solve the problem without using Set?

sobes.tech AI

Answer from AI

You can iterate through the original array and check for each element whether it has been seen before, using an additional object (dictionary) to store already encountered numbers. If the number is new, add it to the result.

Example in JavaScript:

function uniqueArray(arr) {
  const seen = {};
  const result = [];
  for (const num of arr) {
    if (!seen[num]) {
      seen[num] = true;
      result.push(num);
    }
  }
  return result;
}

const input = [1, 2, 3, 2, 4, 1, 5];
console.log(uniqueArray(input)); // [1, 2, 3, 4, 5]

This way, the order is preserved, and duplicates are excluded without using Set.