7

Input:

var array1 = ["12346","12347\n12348","12349"];

Steps:

Replace \n with ',' and Add into list.

Output:

var array2 = ["12346","12347","12348","12349"];

I tried below logic but not reach to output. Looks like something is missing.

var array2 = [];

_.forEach(array1, function (item) {               
       var splitData = _.replace(item, /\s+/g, ',').split(',').join();
       array2.push(splitData);
});

Output of my code:

["12346","12347,12348","12349"]
0

3 Answers 3

10

You could join it with newline '\n' and split it by newline for the result.

var array= ["12346", "12347\n12348", "12349"],
    result = array.join('\n').split('\n');

console.log(result);

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

7 Comments

great idea best use :)
Superb... Solution is working for me... Thanks a lot.
Can we avoid duplicates? if input having some duplicates like var array= ["12346", "12347\n12348", "12349", "12348" ]
then you need some method like array = [...(new Set(array))], or an equivalent in ES5
@AnandSomani You can refer following post to remove duplicates: stackoverflow.com/questions/9229645/…
|
3

If you're using lodash, applying flatmap would be the simplest way:

var array1 = ["12346", "12347\n12348", "12349"];
var array2 = _.flatMap(array1, (e) => e.split('\n'));

console.log(array2);
//=> ["12346", "12347", "12348", "12349"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Comments

1

An alternate to @Nina's answer would be to use Array.push.apply with string.split(/\n/)

var array= ["12346","12347\n12348","12349"];
var result = []

array.forEach(function(item){
   result.push.apply(result, item.split(/\n/))
})

console.log(result);

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.