Home > OS >  Javascript match two arrays by id
Javascript match two arrays by id

Time:11-02

The goal is to match two arrays by id. I need to check if stopId is in both info and times arrays and combine matching arrays.

What should be the proper check to find out if id matches? I've attached an example, I was trying to implement using includes.

Could you please give me an advise?

const info = [
  {
    stopId: 1,
    name: "N1"
  },
    {
    stopId: 2,
    name: "N2"
  },
    {
    stopId: 3,
    name: "N3"
  }
]

const times = [
  {
    stopId: 1,
    time: "T1"
  },
    {
    stopId: 3,
    time: "T2"
  }
]

// Expected
// [
//   {
//     stopId: 1,
//     name: "123",
//     time: "T1"
//   },
//     {
//     stopId: 2,
//     name: "123"
//   },
//     {
//     stopId: 3,
//     name: "123",
//     time: "T2"
//   }
// ]



const res = () => {
  const final = [];
  
  info.forEach((item) => {
     if (times.includes(item.stopId)) { // How to check if stopId matches
       final.push({  })
     }
  })
}

console.log(res())

CodePudding user response:

Try this one:

const result = info.map((item) => {
  const time = times.find((time) => time.stopId === item.stopId)
   return {
     ...item,
     time: time ? time.time : null
   }
})

CodePudding user response:

Attached a working example

const info = [{
    stopId: 1,
    name: "N1"
  },
  {
    stopId: 2,
    name: "N2"
  },
  {
    stopId: 3,
    name: "N3"
  }
]

const times = [{
    stopId: 1,
    time: "T1"
  },
  {
    stopId: 3,
    time: "T2"
  }
]

// Expected
// [
//   {
//     stopId: 1,
//     name: "123",
//     time: "T1"
//   },
//     {
//     stopId: 2,
//     name: "123"
//   },
//     {
//     stopId: 3,
//     name: "123",
//     time: "T2"
//   }
// ]



const res = () => {
  const final = [];

  info.forEach((item) => {
    let temp = { ...item
    };
    times.forEach((el) => {
      if (item.stopId === el.stopId) {
        temp = { ...temp,
          ...el
        };
      }
    })
    final.push(temp);
  })
  console.log(final);
}

res()

CodePudding user response:

With includes you are comparing the objects of time to the stopId of the item. You have to select the stopId of the time first. You can use the operator find for example:

info.forEach((item) => {
     if (times.find(t => t.stopId === item.stopId)) {
       final.push({  })
     }
  })

CodePudding user response:

You should try this code 
var record1 = [
    {
        id: 66,
        name: 'haris'
    },
    {
        id: 873,
        name: 'laxman'
    },
]

var record2 = [
    {
        id: 99,
        name: 'arjit'
    },
    {
        id: 873,
        name: 'laxman'
    },
]
var result = record1.filter((elem, index) => elem.id == record2[index].id );
  • Related