End a function when one of the conditions is true using the Map method

map function javascript
javascript map array of objects
javascript filter
javascript reduce
foreach javascript
angular map function
why use map in javascript
javascript map foreach

I'm new to JS and am trying to write a function that returns true whenever a string has a letter 'b' exactly 3 characters away from any letter 'a', and false if not. For example: "lsufa kfba" = true "lsufakfba" = true "viajs inabn" = false

I've read that the return statement ends the function but it only adds it to the array index in this case. How can I get it to end the function entirely here? Thanks for any help.

var a = "lsufa kfba";
var b = (a.split(' ').join('')).split('a'); // returns ["lsuf", "kfb", ""];

b.map(function(c, i) {
  if (c[2] == 'b') {
    console.log('value: ' + c[2] + ' is b; true');
    return true;
  } else {
    return false;

While the approach I've provided can be simplified using other methods, since you mentioned you are new to JS, I have provided a more long-winded answer which should help you understand what is going on.

In the snippet below I've created a function checkString() which accepts a string as an argument, and returns true or false if the string matches your criteria.

The first part of the function involves looping over the string and getting each character in the string. At each iteration (step in the loop) we check if this character is equal to 'a'. We also store the letter located at the position offset by three in the variable possibleB which will hold the letter 3 spots away from the letter 'a'.

We then use an if statement to check if the current letter (currentLetter) that we are looking at is 'a' and the letter 3 away from the current letter(possibleB) is 'b'. If this is the case, we can return true.

Take a look at the snippet below and the comments to get a better understanding of what is going on:

//whenever a string has a letter 'b' 3 characters away from any letter 'a' return true
function checkString(str) {
  str = str.replace(/\s/g, ''); // remove all spaces from the string (so a ccb = accb which is now true)
  for(var i = 0; i < str.length; i++) {
    if(i+3 > str.length-1) { // If the index+3 is greater than the string length, then there is is no 'b'
      return false;
    var currentLetter = str[i];
    var possibleB = str[i+3]
    if(currentLetter == 'a' && possibleB == 'b' || currentLetter == 'b' && possibleB == 'a') { // if the current letter is a and the letter 3 stops away from our current letter is 'b', return true
      return true;
  return false; // If our for loop hasn't quit by returing yet, we know the string doesn't match our test case

// Test cases
console.log(checkString("lsufa kfba"));
console.log(checkString("lsufa kffa lsufa kfba")); // test multiple spaces
console.log(checkString("viajs inabn"));
console.log(checkString("a ccb"));
console.log(checkString("b cca")); // test b before a

JavaScript for Sound Artists: Learn to Code with the Web Audio API, Learn to Code with the Web Audio API William Turner, Steve Leonard. being applied to . In the following example, a map method is applied to an array and all three freqs = [100, 200, 300]; var newFreqs = freqs.map(function(val, index, arr) { var message effectively, you need to set a condition to terminate the recursion . Mapping an array of numbers using a function containing an argument. The following code shows how map works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as map loops through the original array.

Solution with regex:

const test = ["lsufa kfba", "lsufakfba", "lsufakkkkfba", "lsufbkfaa"];

function foo(str) {
  let trimmed = str.replace(/\s/g, '');
  return /a.{2}b/.test(trimmed) || /b.{2}a/.test(trimmed);

test.forEach(a=>console.log(a, foo(a)));

System Analysis and Modeling. Languages, Methods, and Tools for , Any map can be a plugin with its start points and end points connected to more than one plugin map with pre-conditions used to choose the correct map(s) for  If you’re starting in JavaScript, maybe you haven’t heard of .map(), .reduce(), and .filter().For me, it took a while as I had to support Internet Explorer 8 until a couple years ago.

You are looking for Array.some()

const a = "lsufa kfba";

function foo(str) {
  let index;
  return str.replace(/\s/g, '').split('').some((l, i) => {
    if (l === 'a') {
      index = i;
    if (l === 'b' && i - 3 === index) return true;


Deep Dive into JavaScript's Array Map Method, The Map Function is one of the many Methods existing on the Every once in a while you'll come across a situation where it comes in our array methods toolbelt, and it's important that we use the right tool for each use case. As a result we end up transforming our array of objects into an array of strings. NOTE : You can pass one or more iterable to the map() function. Returns : Returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.) NOTE : The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) . CODE 1

Array.prototype.map(), The map() method creates a new array populated with the results of calling a provided map calls a provided callback function once for each element in an array, in order, true, // configurable: true // }); // For best browser support, use the following: A[k] = mappedValue; } // d. Terms · Privacy · Cookies  Excel’s IF function is like the Swiss Army knife of Excel functions. Really, it is used in many situations. Often, you can use Excel’s IF function with other functions. IF, structurally, is easy to understand. The Excel IF function takes three arguments: A test that gives a true or false answer. For example, the test …

Microeconomics: An Intuitive Approach with Calculus, Given what you might have learned in one of the end-of-chapter exercises in Chapter 11 about the function x 5 f1,2 5 a/11 1 e21,2b22, can Then, with the first order conditions written with w and r on the right-hand sides, divide What do the horizontal slices—the map of isoquants—of this production process look like? starts with the main function and develops the functions on each successive level beneath the main function The variable data refers to the list [10, 20, 30]. The expression data[1:3] evaluates to

Correct Hardware Design and Verification Methods: 10th IFIP WG10.5 , Since basic blocks always terminate, (PARTIALIZEa) maps some x to Defined(a(x​)). Given a block A and a condition c, (WHILE cA) maps some parameter x to some value Defined(y) by iterating A until the value y is reached with ¬(c y). Given an arbitrary initial value init for the local variable, the function (​LOCVARinitA)  As previously mentioned, the map() function uses integer math. So fractions might get suppressed due to this. For example, fractions like 3/2, 4/3, 5/4 will all be returned as 1 from the map() function, despite their different actual values.

  • If you're just trying to omit what doesn't meet your requirement then use .filter() instead of .map()
  • @str that won't meet the position requirement whenever a string has a letter 'b' 3 characters away from any letter 'a'
  • why is the first true, but the third false?
  • The first one should be false since you have " ", "k", "f" and "b" after "a", i.e. "b" is the fourth character after "a".
  • str.replace(' ', '') replaces only first space
  • very helpful, will note that for next time. Thank you very much!
  • Great approach, but does not cover case where the b comes before the a.