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

206
Views
TS (JS question) - Get 2 array of objects return 4 arrays - matches and unmatches from each one

Interface -

interface I {
  name: string;
  age: number;
  size: string;
  location?: string;
}

Empty arrays -

let firstArrayMatches: I[] = [];
let firstArrayUnmatches: I[] = [];

let secondArrayMatches: I[] = [];
let secondArrayUnmatches: I[] = [];

Arrays -

const firstArray: I[] = [
  {
    name: 'daniel',
    age: 30,
    size: 'm'
  },
  {
    name: 'tamir',
    age: 30,
    size: 'm'
  },

]


const secondArray: I[] = [
  {
    name: 'daniel',
    age: 30,
    size: 's'
  },
  {
    name: 'ariel',
    age: 28,
    size: 'm'
  },
]

Create new map from second array (Ignore second string it's for something else in mt real code) -

const map = new Map<string, string>(
  secondArray.map(
    ({
      name
    }) => [
      name,
      'firstArray'
    ])
)

Run on first array -

for (const o of firstArray) {
  const match = map.get(
    o.name
  )

  if(match) {
    firstArrayMatches.push(o);
  } else {
    firstArrayUnmatches.push(o);
  }
}

Log -

First array - console.log(JSON.stringify(firstArrayMatches))

"match: [{"name":"daniel","age":30,"size":"m"}]"

Second array - console.log(firstArrayUnmatches)

[{
  "name": "tamir",
  "age": 30,
  "size": "m"
}] 

Right now my function is able to return only matches and unmatches from the first array, how can I get the second array matches and unmatches?

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

0

The following solution will work only if there are no duplicates on the name of secondArray. (I hope it because you create a Map from it)

// create index of second array
const secondArrayIndexes = Array.from(map.keys());
// OR const secondArrayIndexes = secondArray.map(({ name }) => name);

for (const o of firstArray) {
  // get index of o.name
  const match = secondArrayIndexes.indexOf(o.name);

  if (match >= 0) {
    firstArrayMatches.push(o);
    secondArrayMatches.push(...secondArray.splice(match, 1));
  } else {
    firstArrayUnmatches.push(o);
  }
}
// finally secondArray become secondArrayUnmatches
// you should create copy first if you use secondArray after this
secondArrayUnmatches = secondArray;
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!