Skip to content

Instantly share code, notes, and snippets.

@J-Pster
Created December 27, 2022 21:05
Show Gist options
  • Save J-Pster/c5a1e0a5497a8ed14993c5aab5b8c236 to your computer and use it in GitHub Desktop.
Save J-Pster/c5a1e0a5497a8ed14993c5aab5b8c236 to your computer and use it in GitHub Desktop.
Compração de Arrays, como saber quem eu crio, quem eu edito e quem eu deleto?

Compração de Arrays, como saber quem eu crio, quem eu edito e quem eu deleto?

A solução é bem simples, e o código está anexado a esse Gist!

const currentArray = [
{ id: 1, name: "John", phone: "123" },
{ id: 2, name: "Jane", phone: "123" },
{ id: 3, name: "Richard", phone: "123" },
];
const newArray = [
{ id: 1, name: "John", phone: "456" },
{ id: 3, name: "Richard", phone: "123" },
{ name: "Bob", phone: "123" },
];
const newElements = newArray.filter((element) => !element.id);
console.log("Elementos Novos ");
console.table(newElements);
// Output: [{id: 4, name: 'Bob', phone: '123'}]
const deleteElements = currentArray.filter((currentElement) => {
return !newArray.some((newElement) => newElement.id === currentElement.id);
});
console.log("Elementos Deletados ");
console.table(deleteElements);
// Output: [{id: 2, name: 'Jane', phone: '123'}]
const updateElements = newArray.filter((newElement) => {
return currentArray.find((currentElement) => {
return (
newElement.id === currentElement.id &&
(newElement.phone !== currentElement.phone ||
newElement.name !== currentElement.name)
);
});
});
console.log("Elementos Atualizados ");
console.table(updateElements);
// Output: [{id: 1, name: 'John', phone: '456'}]
const notChangedElements = currentArray.filter((currentElement) => {
return (
updateElements.every(
(updateElement) => updateElement.id !== currentElement.id
) &&
newArray.find(
(newElement) =>
newElement.id === currentElement.id &&
(newElement.phone === currentElement.phone ||
newElement.name === currentElement.name)
)
);
});
console.log("Elementos Não Alterados ");
console.table(notChangedElements);
// Output: [{id: 3, name: 'Richard', phone: '123'}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment