0

Below is my array:

var array = ["abc.mp3,Lmn.mp3","pqr.mp3","ppp.mp3,ggg.mp3"];

Now I want to count length of this record but I would like to treat comma separated records as not a single record

For eg: abc.mp3, Lmn.mp3 want to to treat as 2 separated records by splitting with comma.

Expected length of array should be: 5

Is there any method which will simplify the process of counting this length instead of doing loop and then splitting each record by comma and then counting length one by one?

2
  • what code have you written to solve this? Commented Mar 3, 2017 at 13:20
  • nothing built in... Commented Mar 3, 2017 at 13:20

2 Answers 2

3

join array as string and then split string to array,then you can calculate the array length.

var array = ["abc.mp3,Lmn.mp3","pqr.mp3","ppp.mp3,ggg.mp3"].join(',').split(',');
console.log(array);
console.log(array.length);

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

6 Comments

Just a pointer, comma is the default join value. You can ignore ',' in join
@Rajesh if to ignore , in join,how to split it into array?
Join joins elements using comma itself as default.
yes,I know it,but join the array with , explicit may be let someone known clearly.
Upvoted for your kind effort efforts towards helping me.Thanks you so much and please keep helping like this :)
|
3

You can loop over array and create a new array that will have split values. Now you just have to do newArray.length

var array = ["abc.mp3,Lmn.mp3","pqr.mp3","ppp.mp3,ggg.mp3"];

var ret = array.reduce(function(p,c){
  return p.concat(c.split(','));
}, [])

console.log(ret.length)

Or, you can create a string and count number of commas and just add 1 to it

var array = ["abc.mp3,Lmn.mp3","pqr.mp3","ppp.mp3,ggg.mp3"];

console.log(array.join().match(/,/g).length + 1)

3 Comments

I was just posting the same reduce code ;) Nice solution!
Upvoted for your kind effort efforts towards helping me.Thanks you so much :)
your solution in different ways,and the code clearly too,so I'll up it too.

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.