Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter Array Javascript/typescript

I have an array that needs to be filtered with specific condition

**Input**
    let arr=[
        "abcde-backup",
        "abcde",
        "fghij-backup",
        "fghij",
        "klmnop-backup",
        "qrstuv"
    ]
    I am trying to achieve output like this
**output**
    [
        "abcde-backup",
        "fghij-backup",
        "klmnop-backup",
        "qrstuv"
    ]
  • If any value has -backup has suffix then it should take that and it
    should avoid the one without backup . Here fghij-backup has value
    with backup so that is the priority.

  • If the value doesnt have backup has suffix then it should take it has
    priority eg:qrstuv

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

I am struck with the second point . I have tried with this code

function getLatestJobId(){ 
    let finalArr=[];
    arr.forEach(val=>{
      if(val.indexOf('-backup') > -1){
         finalArr.push(val);
      }   
    })
    
    return finalArr;
} 

>Solution :

As per the explaination, the requirement is to filter out the words with -backup as suffix.

In case the words don’t have the -backup suffix, allow those words only when there is no alternative backup word present.
E.g.: For abcde, since we already have abcde-backup, don’t allow it in result. But, for qrstuv, there is no backup alternative (qrstuv-backup), so allow it.

So, the code for this would be as follow:

let arr=[
        "abcde-backup",
        "abcde",
        "fghij-backup",
        "fghij",
        "klmnop-backup",
        "qrstuv"
    ]

function getLatestJobId(){ 
    return arr.filter(val => val.endsWith('-backup') || !arr.includes(`${val}-backup`))
}

console.log(getLatestJobId())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading