Jackal21
Jackal21

Reputation: 27

How do I turn an array into a number?

var beasts = 'ant 222, bison, ant 333, ant 555, goose 234';

function countAllBeasts(antMany) {

  var OrigString = antMany.split(', ');

  for (var i = 0; i < OrigString.length; i++){
    var justAnt = OrigString[i];
   ;
    if (OrigString.startsWith('CJ') === true){
      (justAnt.length);

    }
  }
  var forLoop = justAnt[i];
  console.log(forLoop);

  return justAnt;
};

update: I still want to use a for loop as the section requires it and it is more simple than other methods. Hoping for the least amount of change to provide the number of the ant xxx in the string that would result after splitting, running in a for loop, and sorting by ant using startsWith... I know there are other approaches but I am looking for the simplest. I was not clear about it before but am clear about it now.

Upvotes: 0

Views: 151

Answers (3)

Ele
Ele

Reputation: 33726

With Regexp you can accomplish that with only one line of code.

// This will return 4 matches (4 commas) + 1 = count of blocks separated by comma.
new RegExp("\,", "g") 

let count = 'ant 222, bison, ant 333, ant 555, goose 234'.match(new RegExp("\,", "g")).length + 1;
console.log(count);

According to your approach: Using a basic for-loop

function countAllBeasts(antMany) {
  var origString = antMany.split(', ');
  var ants = [];
  
  for (var i = 0; i < origString.length; i++) {
    if (origString[i].startsWith('ant'))
       ants.push(origString[i]);
  }
  
  return ants;
}

var beasts = 'ant 222, bison, ant 333, ant 555, goose 234';
console.log(countAllBeasts(beasts));

You can accomplish that using function filter

function countAllBeasts(antMany) {
  var origString = antMany.split(', ');
  var ants = origString.filter((block) => block.trim().startsWith('ant'));

  return ants;
}

var beasts = 'ant 222, bison, ant 333, ant 555, goose 234';
console.log(countAllBeasts(beasts));

Upvotes: 2

Pac0
Pac0

Reputation: 23149

There are already builtin functions for that.

Use a String.prototype.split() function to create an array, using comma as separator, then count the number of elements in the array with Array.length.

var beasts = 'ant 222, bison, ant 333, ant 555, goose 234';
var beastsArray = beasts.split(',');
console.log(beastsArray.length);

Upvotes: 1

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

Try to split using split function. It will return an array. You dont need to push using for loop to a separate array.

var beasts = 'ant 222, bison, ant 333, ant 555, goose 234';
var array = beasts.split(",");
console.log(array.length); // Prints 5 in the console

Upvotes: 1

Related Questions