Estoy luchando por encontrar una forma limpia de reducir o filtrar una matriz para que no contenga valores establecidos duplicados, cuando 2 de los valores coinciden. Aquí hay un ejemplo de los datos que estoy usando. Estoy tratando de eliminar cualquier duplicado donde el título y el género coincidan.
[ { "title": "american-hustle", "genre": "arts", "user": "penny" }, { "title": "american-hustle", "genre": "comedy", "user": "brian" }, { "title": "platoon", "genre": "war", "user": "tom" }, { "title": "american-hustle", "genre": "arts", "user": "sarah" }, { "title": "american-hustle", "genre": "arts", "user": "john" } ]Entonces, en este caso, los dos elementos finales deben eliminarse, ya que tanto el título como el género coinciden con los de una entrada existente. Tenga en cuenta que el segundo elemento debe permanecer como american-hustle con una comedia de género, sigue siendo único.
He intentado encontrar una pregunta similar, pero estoy luchando por encontrar una. Cualquier ayuda sería muy apreciada.
A continuación se presenta una posible forma de lograr el objetivo deseado.
Fragmento de código
const myTransform = arr => ( Object.values( arr.reduce( (acc, {title, genre, ...rest}) => ( acc[`${title}${genre}`] ??= {title, genre, ...rest}, acc ), {} ) ) ); // explanation of code is below /* transform array to remove dupes const myTransform = arr => ( Object.values( // extract only the values of the below intermediate result-object arr.reduce( // use ".reduce()" to iterate with "acc" as accumulator // de-structure the iterator to access title, genre, other props (acc, {title, genre, ...rest}) => ( // conditionally assign value to 'acc' with key as combination of // title=genre and value as the original object's key-value pairs acc[`${title}${genre}`] ??= {title, genre, ...rest}, // NOTE: Using "??=" ensures the first occurance of a dupe is retained // If one would use "=" instead, the last occurance shall be retained // always return "acc" acc ), {} // initialize "acc" as an empty object ) ) // implicit return of the object-values array ); */ const myArr = [ { "title": "american-hustle", "genre": "arts", "user": "penny" }, { "title": "american-hustle", "genre": "comedy", "user": "brian" }, { "title": "platoon", "genre": "war", "user": "tom" }, { "title": "american-hustle", "genre": "arts", "user": "sarah" }, { "title": "american-hustle", "genre": "arts", "user": "john" } ]; console.log( 'removed dupes using title-genre combination', myTransform(myArr) ); .as-console-wrapper { max-height: 100% !important; top: 0 }Explicación
Se agregaron comentarios en línea al fragmento anterior.