Ask Your Question
3

How can we determine if the values in an array correspond to properties of objects in another array?

asked 2023-06-30 23:56:36 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-01 00:00:02 +0000

devzero gravatar image

One possible solution is to iterate through each object in the second array and check if each property exists as a value in the first array. This can be done using nested loops and the includes() method in JavaScript:

const array1 = ["color", "size", "weight"];
const array2 = [
  { color: "red", size: "medium", weight: 10 },
  { color: "blue", size: "large", weight: 20 },
  { color: "green", size: "small", weight: 5 }
];

for (let i = 0; i < array2.length; i++) {
  let obj = array2[i];
  for (let prop in obj) {
    if (array1.includes(prop)) {
      console.log(`${prop} exists in array1`);
    } else {
      console.log(`${prop} does not exist in array1`);
    }
  }
}

In this example, the first loop iterates through each object in the second array, and the second loop iterates through each property of the object. The includes() method checks if the property exists in the first array. If it does, a message is printed indicating that the property exists. If it doesn't, a message is printed indicating that the property does not exist.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-30 23:56:36 +0000

Seen: 7 times

Last updated: Jul 01 '23