1

I have an array of strings :
listOfTypes = ['blogPost', 'work']

And I have a routeName routeName = blogPost-slug or routeName = blogPost;

When routeName contains = blogPost I want to return string "page".
If routeName start with string- (example: blogPost-), I want to return the type (from listOfTypes)

I made a forEach function that works. Only, I get several results (it's normal) when I only want one (if it is present in the array, then I return either the type or page)

listOfTypes = ['blogPost', 'work'];

// routeName is retrieved dynamically. This is for example, "blogPost" or "blogPost-slug" or "work-slug"

listOfTypes.forEach(type => {
      // Check if route name starts with type + "-" because it's separator with subroute 
      // (/blogPost is a page, /blogPost-slug is a blogPost so check for blogPost-)

      if(routeName.startsWith(type + '-')) {
        return console.log(type);
      } else {
        return console.log('page');
      }
    });

// result: 'blogPost' and 'page'
// expected result: 'blogPost'

How can I do this and only get either the type or "page" if it doesn't match?

Thank you

1 Answer 1

1

Using Array#find:

const listOfTypes = ['blogPost', 'work'];

const getType = route => 
  listOfTypes.find(type => route.startsWith(`${type}-`)) ?? 'page';

console.log( getType('blogPost') );
console.log( getType('blogPost-slug') );
console.log( getType('work-slug') );

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! It's exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.