Javascript - Reduce array of arrays - javascript

Array input: [["test","test"],["test2","test"],["test2","test2"],["test","test2"]]
Array output: ["test test","test2 test","test2 test2","test test2"]
I'm able to obtain this output with:
output = input.join("|").replace(/,/g," ").toString().split("|")
However, I don't really like this workaround because:
It seems unnatural
If one of the arrays contains a comma itself, it will be also
removed
If one of the arrays contains a pipe itself, the split will be not as expected
How can I get the output without those handicaps?

Instead of joining the outer array, you can use map to join each inner array separately:
var arr = [["test","test"],["test2","test"],["test2","test2"],["test","test2"]];
var output = arr.map(subarr => subarr.join(' '));

Related

Taking a string and diving it into a array given an regex

I have the following structure, either a single string array ['stufff sjktasjtjser ((matchthis))'], or the same structure in a nested array ['stufff', ['more stuff ((matchhere))'], '((andanother))'];
I can loop and match all regex in the brackets and even replace the text:
//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matchs.forEach(match=>currentArrayElement=currentArrayElement.replaceAll(match[0],'whatwhat'))
console.log(currentArrayElement)//'stufff sjktasjtjser whatwhat'
//but what I actually want is
// currentArrayElement = ['stufff sjktasjtjser','whatwhat'];
Does anyone knows how I can achieve that? Or any template lib that can do that within nested arrays? I need to output sometimes an array of a string ['tss'] and sometimes an array with an object [{}].
Thanks.
The issue was that I needed to change the array in that index not the entire array.
Here is what I did then:
//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matches.forEach((match) => {
currentArrayElement[i] = c.split(match[0]).flatMap(
(value, index, array) => (array.length - 1 !== index
? [value, 'whatwhat',]
: value),
);
});

underscorejs - How to remove array?

underscorejs - How to remove array?
I have an array of objects. I would like to remove an array. Please refer my code below for more details,
array = [{a:10,b:20},{c:10,b:20},{a:10,d:20}];
Expected output: {a:10,b:20},{c:10,b:20},{a:10,d:20}
As I understand You need output without []. To manage that first stringify array, next cut first and last letter.
var array = [{a:10,b:20},{c:10,b:20},{a:10,d:20}];
var str=JSON.stringify(array);
console.log(str.substring(1,str.length-1));
Final string has no [] signs but this is not valid JSON structure. In JSON must be one root element like [] or {}.

Javascript trouble when copying element from one array to another. Extra square brackets, extra dimensions?

Starting out with:
ArrayA = [ ["Element0"], ["Element1"], ["Element2"] ];
and
ArrayB = [];
After a for-loop:
ArrayB[i] = ArrayA.splice(x,1);
then
ArrayB = [ [["Element0"]], [["Element1"]], [["Element2"]] ]
Any clue WHY this is happening?
Array.splice returns an array of the removed items. In ArrayA, each item is an array, so Array.splice returns an array containing that array. For example,
ArrayA.splice(0, 1) returns [["Element0"]]. If you use a look to populate ArrayB like this, you'll end up with an array in which each element is an array containing a single array, which is what you have.
If you always use Array.splice for a single element and you want that element to be returned, you could write ArrayA.splice(0, 1)[0] to get the first element.
Also, do you really want ArrayA to be an array of arrays? Or do you want it to be an array of strings? If so, that would simply be ArrayA = ["Element0", "Element1", "Element2"]; and the result of ArrayA.splice(0, 1) would be "Element0".

How to concat an array within an array

Here is the problem. How do I do this below. The array within an array is throwing me off.
[...] alert to the screen the entire first movie in eightiesMovies, but only using the eightiesMovies variable. For now, use the concatenation operator to unite the words into one string. Remember to be attentive to necessary whitespace [...]
var movie1 = [ 16, "Candles"];
var movie2 = [ 3, "Men", "and", "a", "Baby"];
var eightiesMovies = [ movie1, movie2];
I have tried these answers to no avail
alert(eightiesMovies[0][0].concat("", eightiesMovies[0][1]));
alert(eightiesMovies([0][0]).concat("", eightiesMovies([0][1]));
Very simple:
movie1.concat(movie2) // will combine the 2 arrays
movie2.join(''); will join the element in the array
result:
movie2.join('') => "3MenandaBaby"
eightiesMovies[0][0] + " " + eightiesMovies[0][1]
The concatenation operator in this case is +, which is used to concatenate strings together. Since this is a nested array, you can chain array access. You want the first movie (which is an array in the first element of the eightiesMovies array at position 0). Then just concatenate each value of that array. You would have to know the length of the arrays ahead of time. That is to say the above would only print out part of the second movie.

Converting an array to a string in Javascript

I have a multi-dimensional array like this:
1 2 3
4 5 6
Now I need to convert this array into a string like 1,2,3;4,5,6.
Can any one suggest how to do this, please?
simply use the join method on the array.
> [[1,2,3],[4,5,6]].join(';')
'1,2,3;4,5,6'
It's lucky that you simply don't have to consider how the apply the join method on the inner lists, because a list is joined by comma by default. when a list is coerced into a string, it by default uses commas to separate the items.
As it was already mentioned by qiao, join() is not recursive.
But if you handle the recursion yourself you should acquire the desired result, although in a rather inelegant way.
var array = [[1,2,3],[5,6,7]];
var result = [];
array.forEach(
function(el){
result.push(
el.join(",")
);
});
result.join(";");
If you need to serialize an array into a string and then deserialize it later to get an array from the string you might want to take a look at JSON:
http://www.openjs.com/scripts/data/json_encode.php
Try this:
array.toString();
See here for reference: http://www.w3schools.com/jsref/jsref_tostring_array.asp
See answer by qiao for a much nicer approach to multidimensional arrays like this.

Categories