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

115
Views
Merge string in array javascript

i have an array like this:

let data = ['week1_aopCrop', 'week1_actCrop', 'week2_aopCrop', 'week2_actCrop']

the output should be:

['week1', 'week2']

anyone can help? thanks!

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

0

1) You can easily achieve the result using reduce and Set as

let data = ["week1_aopCrop", "week1_actCrop", "week2_aopCrop", "week2_actCrop"];

const result = [...data.reduce((acc, curr) => {
    acc.add(curr.split("_")[0]);
    return acc;
  }, new Set()),
];

console.log(result);

2) You can also use map here as:

let data = ["week1_aopCrop", "week1_actCrop", "week2_aopCrop", "week2_actCrop"];

const result = [...new Set(data.map((s) => s.split("_")[0]))];
console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

Using forEach

let data = ['week1_aopCrop', 'week1_actCrop', 'week2_aopCrop', 'week2_actCrop'];
let out = [];
data.forEach((item,index)=>{
    if(!out.includes(item.split("_")[0])) {
    out.push(item.split("_")[0]);
  }
});
console.log(out);

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!