1

I have array

 const example = [{ day: 5, month: 1, key: 1 },{ day: 5, month: 1, key: 2 },{ day: 3, month: 3, key: 3 },{ day: 5, month: 1, key: 4 },{ day: 3, month: 3, key: 5 },{ day: 11, month: 4, key: 6 }];

how to check the elements of the day and month when the same ? if the year and month are repeated I would like the result return

{err:'the same',index:[0,1,2,3]}

My code not working.

const duplicates = Object.entries(array).reduce((acc, item, index) => {
  if (acc[1].year === item[1].year && acc[1].month === item[1].month) {
    return [
      {
        index:[acc[0],acc[1]],
        err: "the same"
      }
    ];
  }
return acc;});

2 Answers 2

1
  • Iterate over the array using Array#reduce to get a Map of the day-month as the key and its occurrence indices as the value.
  • Using Array#filter, get the entries that have more than one index.
  • After that, return the list using Array#map.

const array = [ { day: 5, month: 1, key: 1 }, { day: 5, month: 1, key: 2 }, { day: 3, month: 3, key: 3 }, { day: 5, month: 1, key: 4 }, { day: 3, month: 3, key: 5 }, { day: 11, month: 4, key: 6 } ];

const duplicates = [...array
.reduce((map, { day, month }, index) => {
  const key = `${day}-${month}`;
  map.set(key, [...(map.get(key) || []), index]);
  return map;
}, new Map)
.values()]
.filter(indices => indices.length > 1)
.map(indices => ({ err: "the same", index: indices }));

console.log(duplicates);

Sign up to request clarification or add additional context in comments.

Comments

0

I would use the Map constructor to build a map keyed by (unique) year-month values, and where the associated values are arrays of error objects, initialised with an empty index array. Then populate those index arrays, and get those that have more than one entry. This involves no reduce:

const example = [{ day: 5, month: 1, key: 1 },{ day: 5, month: 1, key: 2 },{ day: 3, month: 3, key: 3 },{ day: 5, month: 1, key: 4 },{ day: 3, month: 3, key: 5 },{ day: 11, month: 4, key: 6 }];

const map = new Map(example.map(o => 
    [o.month * 100 + o.day, {err: "the same", index: []}]
));
example.forEach((o, i) => map.get(o.month * 100 + o.day).index.push(i));
const dupes = Array.from(map.values()).filter(o => o.index.length > 1);
console.log(dupes);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.