Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
js - assign property when comparing 2 arrays with set and for of

Example data -

const arr = [{name: "q",age: 10,size: "M",},{name: "w",age: 10,size: "S",},{name: "e",age: 10,size: "M",},];
const arr2 = [{name: "q",age: 10,size: "M",location: "NYC"},{name: "w",age: 10,size: "S",location: "DC"},{name: "i",age: 10,size: "S",location: "NYC"},{name: "x",age: 10,size: "S",location: "NYC"},];

The logic -

const set = new Set(arr2.map(({name, size}) => size + "/" + name));

const x = [], y = [];
for (let obj of arr) {
    (set.has(obj.size + "/" + obj.name) ? x : y).push(obj);
}

Result -

x:
[
  {
    "name": "q",
    "age": 10,
    "size": "M"
  },
  {
    "name": "w",
    "age": 10,
    "size": "S"
  }
]
y:
[
  {
    "name": "e",
    "age": 10,
    "size": "M"
  }
]

How can I assign the location to arr. wanted result -

   x:
    [
      {
        "name": "q",
        "age": 10,
        "size": "M",
        "location": "NYC"
      },
      {
        "name": "w",
        "age": 10,
        "size": "S",
        "location": "DC"
      }
    ]
    y:
    [
      {
        "name": "e",
        "age": 10,
        "size": "M",
      }
    ]

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use an object or Map instead of Set. Then you can save the location along with the name and size.

const arr = [{name: "q",age: 10,size: "M",},{name: "w",age: 10,size: "S",},{name: "e",age: 10,size: "M",},];
const arr2 = [{name: "q",age: 10,size: "M",location: "NYC"},{name: "w",age: 10,size: "S",location: "DC"},{name: "i",age: 10,size: "S",location: "NYC"},{name: "x",age: 10,size: "S",location: "NYC"},];

const map = new Map(arr2.map(({name, size, location}) => [size + "/" + name, location]));

const x = [], y = [];
for (let obj of arr) {
  let location = map.get(obj.size + "/" + obj.name);
  if (location) {
    obj.location = location;
    x.push(obj);
  } else {
    y.push(obj);
  }
}
console.log(x);
console.log(y);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!