0

I have an array with elements. These elements are object paths. Some are just one level deep : ui.main and some are multiple levels deep : ui.main.tab. Now my intention is to perform an action whenever the path is just one level deep.

so for example ui.main => perform action. ui.tab.main => do nothing etc.

I know i have to use some sort of loop and a regular expression, but i am having trouble combining the two as i am not comfortable working with those.

2
  • By elements, do you mean strings? ['foo.bar', 'foo.bar.baz']? Commented Aug 9, 2019 at 7:56
  • Yes sorry, the elements are basically strings as in your example @CertainPerformance Commented Aug 9, 2019 at 7:57

3 Answers 3

2

You could split the string on the . and check the length:

const arr = ['ui.main.tab', 'ui.main', 'test.main', 'test.main.tab'];

arr.forEach(el => {
  if (el.split('.').length === 2) console.log(el);
});

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

Comments

2

I'd check whether the indexOf a . is the same as the lastIndexOf a . (and is not -1), fulfilling the condition when there's exactly one . in the string being checked:

const arr = ['ui.main', 'ui.tab.main'];
arr.forEach((str) => {
  const index = str.indexOf('.');
  if (index !== -1 && str.lastIndexOf('.') === index) {
    console.log('doing something', str);
  }
});

Comments

1

const arr = ['ui.main', 'ui.tab.main', 'ui.foo'];

arr.forEach((str) => {
  const count = (str.match(/\./g) || []).length;
  if (count === 1) {
	console.log("do something with: " + str);
  }
});

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.