Home > OS >  Merge string in array javascript
Merge string in array javascript

Time:12-04

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!

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related