I
I
Ilya2019-04-18 20:20:21
React Native
Ilya, 2019-04-18 20:20:21

How to merge and check an array?

Faced such a problem.
I have a main array of data:
It is displayed on the main page of the application.

Array [
  Object {
    "idSite": 123456,
    "status": "C",
    "type": 1
  },
  Object {
    "idSite": 123451,
    "status": "O",
   "type": 4   
  },
  Object {
    "idSite": 123458, 
    "status": "N", 
    "type": 1
  },
  Object {
    "idSite": 123455,
    "status": "C", 
    "type": 3,
  }
]

And there is a second array that is displayed on another page:
It looks like this:
[
  {
"idSite": 123456,
"typetext": "System armed",
"status": "C"
},
  {
"idSite": 123456,
"typetext": "System unarmed",
"status": "O"
},
  {
"idSite": 123455,
"typetext": "Battery low",
"status": "C"
}

The question is how can I transfer the type values ​​​​from the first array to the second. But not just to merge, but by checking idSite. That is, if idSite from the first array is equal to idSite of the second array, then we add to the second idSite the value of type from the first array. So that in the end my second array becomes like this:
[
  {
"idSite": 123456,
"typetext": "System armed",
"status": "C",
 "type": 1
},
  {
"idSite": 123456,
"typetext": "System unarmed",
"status": "O",
 "type": 1
},
  {
"idSite": 123455,
"typetext": "Battery low",
"status": "C",
 "type": 3,
}

For technical reasons, on the backend side, there is no way to add the type value to the second array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-18
@ynizhenie

For technical reasons, on the backend side, there is no way to add the type value to the second array.

I think you have been deceived.
array2.forEach(el2 => {
 el2.type = array1.find(el1 => el1.idSite === el2.idSite);
});

But if there is a lot of data, then this option will work faster:
const array1Clone = array1.slice(0);

array2.forEach(el2 => {
 const index = array1Clone.findIndex(el1 => el1.idSite === el2.idSite);
 
 if (index > -1) {
    el2.type = array1Clone.splice(index,1)[0].type;
 }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question