I have this initial array and want to extract the repeating flights based on from.flightNo and to.flightNo
const myArray = [
{ from: { flightNo: 'A11' }, to: { flightNo: 'B11' }, code: 23 },
{ from: { flightNo: 'A12' }, to: { flightNo: 'B45' }, code: 22 },
{ from: { flightNo: 'A12' }, to: { flightNo: 'B52' }, code: 21 },
{ from: { flightNo: 'A11' }, to: { flightNo: 'B11' }, code: 20 },
{ from: { flightNo: 'A14' }, to: { flightNo: 'B44' }, code: 25 },
{ from: { flightNo: 'A15' }, to: { flightNo: 'B69' }, code: 24 },
{ from: { flightNo: 'A14' }, to: { flightNo: 'B44' }, code: 26 },
];
result:
[
{ from: { flightNo: 'A11' }, to: { flightNo: 'B11' }, code: 23 },
{ from: { flightNo: 'A11' }, to: { flightNo: 'B11' }, code: 20 },
{ from: { flightNo: 'A14' }, to: { flightNo: 'B44' }, code: 25 },
{ from: { flightNo: 'A14' }, to: { flightNo: 'B44' }, code: 26 },
]
I wrote this but I can only get the first repeating one and doesn't look very pretty.
const duplicates = myArray
.map((item) => {
let count = 0;
for (let i = 0; i < myArray.length; i++) {
if (count > 1) {
count = 0;
return item;
}
if (
myArray[i]?.from?.flightNo == item?.from?.flightNo &&
myArray[i]?.to?.flightNo == item?.to?.flightNo
)
count++;
}
})
.filter((notUndefined) => notUndefined !== undefined);
Any suggestions?