Compare objects in two arrays and return based on match in javascript

后端 未结 3 605
梦谈多话
梦谈多话 2021-01-29 00:34

I am using React for this, but the concept is in javascript. So hopefully I can leave React code out for simplicity sake.

I have two arrays that I need to filter out. My

3条回答
  •  悲&欢浪女
    2021-01-29 01:04

    You can use vanilla js for this one. When you do this loop, check out the comparisons you are making:

    Iterations (omitting ID): ArrayOne vs ArrayTwo

    1. 1 compares with 3
    2. 2 compares with 4
    3. 3 compares with undefined (will error since it's asking for undefined.id)
    4. 4 compares with undefined (will error since it's asking for undefined.id)

    If your elements are always going to be in order, you can loop over the first array and build out a binary search to quickly find elements in the second. This brings your time complexity to o(n * log(n)) and will be better in the long run. If you're just looking to hit MVP, you can do this:

    const myFilter = (arrayOne, arrayTwo) => {
      return arrayOne.map((objectOne) => {
    
        // Using findIndex over includes to be able to pass callback
        // to compare the IDs
        // returns -1 if not found
    
        const matchIndex = arrayTwo.findIndex((objectTwo) => {
          return objectOne.id === objectTwo.id
        })
    
    
        if (matchIndex >= 0) {
          return 
    Match
    } else { return
    NoMatch
    } }) }

    Your time complexity will be o(n^2) in this approach, but that may be the best case depending on your circumstances. You can also use a temporary data structure, such as a Set to get o(n) time with the tradeoff of o(n) space.

提交回复
热议问题