Set object property in an array true/false, whether the id matches with any id from another array of objects in JavaScript?



The task we are going to perform in this article is ‘set object property in an array true/false whether the id matches with any if from another array of objects in JavaScript’. Before we jump into the article let’s have a glance at the object and array in JavaScript.

An object in JavaScript is a separate entity having properties and a type. JavaScript objects have properties that specify their attributes.

Multiple values can be kept in a single variable by using arrays. Compare that to a variable that only has room for one value. Each item in an array has a number associated with it that you can access by using, referred to as a numeric index. Arrays in JavaScript begin at index zero and can be changed using a variety of operations.

Syntax

Following is the syntax for array in JavaScript -

const array_name = [item1, item2, ...]; 

let’s look into the article to learn about “how to set object property in an array true/false whether the id matches with any id from another array of objects in JavaScript”. you can use reduce () along with map().

reduce() in JavaScript

The reduce() method in JavaScript is used to apply a (call back) function to each element in an array, resulting in a single output value. Itexecutes the callback function once for each element present in the array, excluding holes in the array.

It then stores the result of previous iteration into accumulator argument and carries it over to next iterations until all values are processed.

Syntax

Following is the syntax for reduce() in JavaScript -

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

map() in JavaScript

Any sort of data can be used as a key or value in a map, which also remembers the order in which its elements appear. It is used to create a new array by repeatedly going through each element in an array.

Syntax

Following is the syntax for map() in JavaScript -

array.map(function(currentValue, index, arr), thisValue)

For better understanding, let’s look into the following examples.

Example

In the following example, we are using the reduce() along with the map().

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      let array_1=[{"id":1,"name":"bmw"},{"id":22,"name":"audi"},{"id":3,"name":"bullet"}]
      let array_2=[{"id":1,"name":"benz"},{"id":82,"name":"rx100"},{"id":3,"name":"bullet"},]
      document.write("Contents of the first array: ", JSON.stringify(array_1),"<br>");
      document.write("Contents of the second array: ", JSON.stringify(array_2),"<br>");
      const o = array_2.reduce((r, e) => (r[e.id] = true, r), {})
      const result = array_1.map(e => ({ ...e, matches: o[e.id] || false}))
      document.write("Result of the comparison: ",JSON.stringify(result));
   </script>
</body>
</html>

Example

Considering the following example, where we are using loops.

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      let tutorial_1 = [
         { id: 5, car: 'cruze' },
         { id: 2, car: 'beats' },
         { id: 3, car: 'sail' },
      ];
      let tutorial_2 = [
         { id: 1, car: 'city' },
         { id: 80, car: 'verna' },
         { id: 3, car: 'electra' },
      ];
      tutorial_1.forEach(item_1 => {
         for (let i = 0; i < tutorial_2.length; i++) {
            item_1.matches = tutorial_2[i].id === item_1.id
         }
      });
      document.getElementById("tutorial").innerHTML=    JSON.stringify(('matched_array', tutorial_1));
   </script>
</body>
</html>

Example

In the following example where are declaring fixed array and making comparison using the every() method.

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      let fixed = ["abc", "def", "ghi"];
      let Array1 = [{
         bike: "rx100",
         id: "abc"
      }, {
         bike: "pulsar",
         id: "def"
      }, {
         bike: "splendor",
         id: "ghi"
      }];
      let conA1 = Array1.every(elem => fixed.includes(elem.id));
      document.getElementById("tutorial").innerHTML= conA1;
   </script>
</body>
</html>

When the script gets executed, the event gets triggered, which compares the array with a fixed array and gives the value. In this case, it will say "true" on the web browser, as the array matches the fixed array.


Advertisements