Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
Compare dos matrices de objetos y elimínelos si el valor del objeto es igual

Intenté modificar algunas de las soluciones similares aquí, pero sigo atascado, creo que tengo parte de esto resuelto, sin embargo, la advertencia principal es que:

Algunos de los objetos tienen claves adicionales, lo que hace que mi lógica de comparación de objetos sea inútil.

Estoy tratando de comparar dos matrices de objetos. Una matriz es la matriz original y la otra matriz contiene los elementos que quiero eliminar de la matriz original. Sin embargo, hay un problema adicional en el sentido de que la segunda matriz contiene claves adicionales, por lo que mi lógica de comparación no funciona.

Un ejemplo lo haría más fácil, digamos que tengo las siguientes dos matrices:

 const originalArray = [{id: 1, name: "darnell"}, {id: 2, name: "funboi"}, {id: 3, name: "jackson5"}, {id: 4, name: "zelensky"}]; const itemsToBeRemoved = [{id: 2, name: "funboi", extraProperty: "something"}, {id: 4, name: "zelensky", extraProperty: "somethingelse"}];

después de ejecutar la lógica, mi salida final debería ser esta matriz:

[{id: 1, name: "darnell"}, {id: 3, name: "jackson5"}]

Y aquí está el código/lógica actual que tengo, que compara pero no maneja las claves adicionales. ¿Cómo debería manejar esto? Gracias de antemano.

 const prepareArray = (arr) => { return arr.map((el) => { if (typeof el === "object" && el !== null) { return JSON.stringify(el); } else { return el; } }); }; const convertJSON = (arr) => { return arr.map((el) => { return JSON.parse(el); }); }; const compareArrays = (arr1, arr2) => { const currentArray = [...prepareArray(arr1)]; const deletedItems = [...prepareArray(arr2)]; const compared = currentArray.filter((el) => deletedItems.indexOf(el) === -1); return convertJSON(compared); };
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

¿Qué hay de usar filter y some ? Puede extender la condición de filtro en propiedades seleccionadas usando && .

 const originalArray = [ { id: 1, name: 'darnell' }, { id: 2, name: 'funboi' }, { id: 3, name: 'jackson5' }, { id: 4, name: 'zelensky' }, ]; const itemsToBeRemoved = [ { id: 2, name: 'funboi', extraProperty: 'something' }, { id: 4, name: 'zelensky', extraProperty: 'somethingelse' }, ]; console.log( originalArray.filter(item => !itemsToBeRemoved.some(itemToBeRemoved => itemToBeRemoved.id === item.id)) )

O puedes generalizarlo también.

 const originalArray = [ { id: 1, name: 'darnell' }, { id: 2, name: 'funboi' }, { id: 3, name: 'jackson5' }, { id: 4, name: 'zelensky' }, ]; const itemsToBeRemoved = [ { id: 2, name: 'funboi', extraProperty: 'something' }, { id: 4, name: 'zelensky', extraProperty: 'somethingelse' }, ]; function filterIfSubset(originalArray, itemsToBeRemoved) { const filteredArray = []; for (let i = 0; i < originalArray.length; i++) { let isSubset = false; for (let j = 0; j < itemsToBeRemoved.length; j++) { // check if whole object is a subset of the object in itemsToBeRemoved if (Object.keys(originalArray[i]).every(key => originalArray[i][key] === itemsToBeRemoved[j][key])) { isSubset = true; } } if (!isSubset) { filteredArray.push(originalArray[i]); } } return filteredArray; } console.log(filterIfSubset(originalArray, itemsToBeRemoved));

Otra variación más simple del segundo enfoque:

 const originalArray = [ { id: 1, name: 'darnell' }, { id: 2, name: 'funboi' }, { id: 3, name: 'jackson5' }, { id: 4, name: 'zelensky' }, ]; const itemsToBeRemoved = [ { id: 2, name: 'funboi', extraProperty: 'something' }, { id: 4, name: 'zelensky', extraProperty: 'somethingelse' }, ]; const removeSubsetObjectsIfExists = (originalArray, itemsToBeRemoved) => { return originalArray.filter(item => { const isSubset = itemsToBeRemoved.some(itemToBeRemoved => { return Object.keys(item).every(key => { return item[key] === itemToBeRemoved[key]; }); }); return !isSubset; }); } console.log(removeSubsetObjectsIfExists(originalArray, itemsToBeRemoved));

about 4 years ago · Juan Pablo Isaza Report

0

El siguiente ejemplo es una función reutilizable, el tercer parámetro es la clave con la que compara los valores de ambas matrices.

Los detalles se comentan en el ejemplo.

 const arr=[{id:1,name:"darnell"},{id:2,name:"funboi"},{id:3,name:"jackson5"},{id:4,name:"zelensky"}],del=[{id:2,name:"funboi",extraProperty:"something"},{id:4,name:"zelensky",extraProperty:"somethingelse"}]; /** Compare arrayA vs. delArray by a given key's value. --- ex. key = 'id' **/ function deleteByKey(arrayA, delArray, key) { /* Get an array of only the values of the given key from delArray --- ex. delList = [1, 2, 3, 4] */ const delList = delArray.map(obj => obj[key]); /* On every object of arrayA compare delList values vs current object's key's value --- ex. current obj[id] = 2 --- [1, 2, 3, 4].includes(obj[id]) Any match returns an empty array and non-matches are returned in it's own array. --- ex. ? [] : [obj] The final return is a flattened array of the non-matching objects */ return arrayA.flatMap(obj => delList.includes(obj[key]) ? [] : [obj]); }; console.log(deleteByKey(arr, del, 'id'));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!