3

I know there has been a question like this, but mine is a little different, and it already works, but I don't know how to simplify it.

if (location.pathname === `/` || location.pathname ===`/kurikulum/` || location.pathname === `/pengembangan-diri/` || location.pathname === `/statistik/` || location.pathname === `/teknologi/` || location.pathname === `/ekonomi/` || location.pathname === `/desain/` || location.pathname === `/corona/`)

as you can see it is not beautiful, I wonder can we make it without repeating location.pathname?

this is on gatsby, but it is a javascript question

5 Answers 5

7

You can use Array.includes to check if the current pathname exists in a given array.

let pathArr = ['/', '/kurikulum/', '/pengembangan-diri/', '/statistik/', '/teknologi/', '/ekonomi/', '/desain/', '/corona/'];
let testPath = '/desain/';

if (pathArr.includes(testPath)) {
   document.write('path found!');
};

Learn more about Array.includes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

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

2 Comments

what if we want to make it the other way around ? like /path/ that is now in the array?
@MuhZulzidan what do you intend to do here? Can't understand.
3

Use includes(), it will return true or false if the value is in the array.

const pathnames = [
  '/',
  '/kurikulum/',
  '/pengembangan-diri/',
  '/statistik/',
  '/teknologi/',
  '/ekonomi/',
  '/desain/',
  '/corona/'
]

if (pathnames.includes(location.pathname)) {
  // do something
}

Comments

2

you can put all of your paths into a path array then run an indexOf() function to see if something fits

const paths = ['/', '/path', '/path1']
const thePath = '/',

if (paths.indexOf(thepath) >= 0) {
  console.log('the path exists')
} else {
console.log('the path doesnt exist')
}

Comments

2

Another way is that you can use array.filter or array.some.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const searchFunc = (searchItem) => words.filter(word => word === searchItem).length > 0;
if(searchFunc('limit')){
  console.log("Item is found");
}

// expected output: "Item is found"

Comments

-2

You can simplify by define an JavaScript array of objects like below:

{
  path: '/some-path-to-compare`,
}

Then instead of compare by lot of lines, use loop then compare with the path field.

Comments

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.