• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

363
Vistas
TypeScript - find the difference between arrays with duplicates

Edit: Please read the question before closing it! The suggested answer has zero to do with what I asked. I'm not after a single array solution, I'm using two arrays...


I'm deduplicating an array but when I go to find the difference it doesn't find any because whats in the new array is in the old array:

const original = [1,2,2,3,4]

const newArr = Array.from(new Set(original).values());

const diff = original.filter(line => !newArr.includes(line));

What I expect to find is that the difference found is 2. In my real example I'm using crypto wallet addresses, and I need to deduplicate the list, but I also want to print to stdout what the differences are between the original array and the new array.

Example

Given the below input

123asd123asd123
123asd123asd123
890wer890wer809

I expect the following output

Deduplication complete!

Wallet 123asd123asd123 - Duplicate removed
about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Answering my own question. What I wanted to find was the difference between the original array and the array after it was deduplicated so I can print to the user which items were removed. Using the suggested or existing answers from other questions only deduplicates and/or don't account for duplicates and therefore fail to detect them.

My current solution

const original = [
    "apple",
    "apple",
    "banana",
    "orange",
    "apple",
]

// After deduplication, code omitted for clarity
// deduped = Array.from(new Set(original).values());
const deduped = [
    "banana",
    "orange",
    "apple",
]

// Now lets find the differences
let diff = original.slice()
for (let i = 0; i < deduped.length; i++) {
    const item = deduped[i];
    if (diff.includes(line)) {
        diff.splice(diff.indexOf(line), 1);
    }
}

// Display the difference of what is not in the deduced array
console.log(diff);

output

["apple", "apple"]

The above works in TS. No, it doesn't contain type annotations, but also doesn't require adding them either like other answers. May not be the most succinct my this solved my issue.

I am using this for a format function, where I want to see all changes made between two text files by line.

about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda