Shortest way to find duplicates in array of arrays of objects by property

后端 未结 1 1839
遇见更好的自我
遇见更好的自我 2021-01-16 05:02

Hi I have an array of objects. Each object has array of objects. I need to find duplicates of (inner) objects what has the same value in a specific property. I made up to cr

相关标签:
1条回答
  • 2021-01-16 05:26

    If you're looking for clearer, shorter code, you could use flatMap to extract every streamItemName into a single array, then use .find to find if there are any duplicates:

    const streamItemNames = validateStreamItemsResults.streamWebSockets.flatMap(
      socket => socket.streamItems.map(
        item => item.streamItemName.trim().toLowerCase()
      )
    );
    const dupe = streamItemNames.find((name, i, arr) => arr.slice(i + 1).includes(name));
    if (dupe) {
      validateStreamItemsResults.errorMessage = `Duplicate stream items found with the name: ${dupe}`;
      return validateStreamItemsResults;
    }
    

    If you don't need to know the duplicate name, you could make it shorter by making a Set and comparing its .size against the array's length.

    0 讨论(0)
提交回复
热议问题