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

85
Views
How to properly filter the array

Hello everyone there is an array of data of this kind

const arrayPat = [
    {pat: '111', res: 'qwe', tag: '1'},
    {pat: '111', res: 'sda', tag: '2'},
    {pat: '111', res: 'xzc', tag: '3'},
    {pat: '111', res: 'cej', tag: '4'},
    {pat: '222', res: 'qwd', tag: '5'},
    {pat: '222', res: 'asd', tag: '6'},
  ]

need to get something like that

  const resultArray: any = [{pat: '111', res: ['qwe', 'sda', 'xzc', 'cej'], tag: '1'},{pat: '222', res: ['qwe', 'asd'], tag: '1'}]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If exactly what is mentioned in the question is needed, we can slightly tweak the code

const arrayPat = [{
    pat: '111',
    res: 'qwe',
    tag: '1'
  },
  {
    pat: '111',
    res: 'sda',
    tag: '2'
  },
  {
    pat: '111',
    res: 'xzc',
    tag: '3'
  },
  {
    pat: '111',
    res: 'cej',
    tag: '4'
  },
  {
    pat: '222',
    res: 'qwd',
    tag: '5'
  },
  {
    pat: '222',
    res: 'asd',
    tag: '6'
  },
]
const val = []
arrayPat.forEach((curr) => {
  let newPath = val.find(currentItem => currentItem.pat === curr.pat);
  if (!newPath) {
    val.push({
      pat: curr.pat,
      res: [curr.res],
      tag: curr.tag
    })
  } else {
    newPath.res.push(curr.res)
  }

});

console.log(val)

about 4 years ago · Juan Pablo Isaza Report

0

You may need array.reduce instead of filter. Secondly the required value of tag is not clear from the question. You can modify this answer to set proper value of tag

const arrayPat = [{
    pat: '111',
    res: 'qwe',
    tag: '1'
  },
  {
    pat: '111',
    res: 'sda',
    tag: '2'
  },
  {
    pat: '111',
    res: 'xzc',
    tag: '3'
  },
  {
    pat: '111',
    res: 'cej',
    tag: '4'
  },
  {
    pat: '222',
    res: 'qwd',
    tag: '5'
  },
  {
    pat: '222',
    res: 'asd',
    tag: '6'
  },
]

const val = arrayPat.reduce((acc, curr) => {
  if (!acc[curr.pat]) {
    acc[curr.pat] = {
      pat: curr.pat,
      res: [curr.res],
      tag: curr.tag
    }
  } else {
    acc[curr.pat].res.push(curr.res)
  }


  return acc;

}, {});

console.log(Object.values(val))

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!