This question already has an answer here:
JS: Join Array of arrays
(1 answer)
Closed 1 year ago.
Trying to solve this puzzle in JavaScript:
Input: An array containing x amoung of arrays of numbers. Heres example:
[
[1,4],
[6,8],
[10]
]
Expected Output: I would want to run some sort of code to turn it into:
1-4,6-8,10
I've tried join("-") and tried the same thing within a forEach() loop but can't quite get it to work
You can use map the array and join each item by a dash, then join the resulting array.
const arr = [
[1, 4],
[6, 8],
[10]
]
const res = arr.map(e => e.join('-')).join()
console.log(res)
You can use map to iterate over the array, join up each nested array with a dash, and then finally join up the array that map returns into a comma-delimited string.
const arr = [[1,4],[6,8],[10]];
const out = arr.map(a => a.join('-')).join(',');
console.log(out);
Related
This question already has answers here:
All possible combinations of a 2d array in Javascript
(2 answers)
Closed 1 year ago.
I want to transform one array of arrays by doing a specific transform, like the following example:
[[1, 2, 3], [4, 5]] => [14, 15, 24, 25, 34, 35];
Note, the first element of the first array is concatenated to each element of the second array to form a new array, and so on with the second element, third... etc
Use array.concat and for loop
let arrays = [
["a1","b1","c1"],
["a2","b2","c2"],
["a1","b1","c1"],
["a1","b1","c1"],
]
let arr = [];
arrays.forEach(array =>{
arr = arr.concat(array)
})
console.log(arr)
This question already has answers here:
Using spread operator multiple times in javascript?
(4 answers)
Closed 4 years ago.
Here is what I tried:
let a = [[1,2], [3,4]];
a.map(val => ...val)
// => SyntaxError: expected expression, got '...'
// Expected output: [1,2,3,4]
I tried with explicit return statement and surrounding value with parenthesis but none worked...
I just wonder if there is a simple way to return "spreaded array" ?
Edit: Now I have seen this SO question which has got precision on how spread operator works although in doesn't really answer the question on how to "flatten" an array (I modified the title of the question).
This isn't valid syntax, for this to work you need to spread ("unpack" the contents of) your array into a container of some sort (such as an array). However, if you were to do something like:
a.map(val => [...val])
you would not be doing much with your array, and instead, you would end up with copies of the same array. Thus, you can use different methods other than .map such as .reduce or .flatMap/.flat to achieve your desired output:
Using .reduce with the spread syntax:
let a = [[1,2], [3,4]];
let res = a.reduce((acc, val) => [...acc, ...val], []);
console.log(res)
Using .flatMap():
let a = [[1,2], [3,4]];
let res = a.flatMap(val => val); // map the contents (without the holding array) [[1, 2], [3, 4]] -> [1, 2, [3, 4]] -> [1, 2, 3, 4]
console.log(res)
.flatMap() is, however, useless here, and thus using .flat() would simply suffice:
let a = [[1,2], [3,4]];
let res = a.flat();
console.log(res)
Try to use a.flatMap(x=>x); to flat array and map elements or flat (with no mapping)
a.flat();
let a = [[1,2], [3,4]];
let r=a.flat();
console.log(r);
In flat arg you can set deep-level of flatting - setting Infinity will flat any nested array
let a = [[1,2,[3,4,[5,[6]]]], [[7,[8]],9]];
let r=a.flat(Infinity);
console.log(r);
As written in comments, functions can only return one value.
But there is a simple trick what you can use:
let a = [[1,2], [3,4]];
a.reduce((a,b) => a.concat(b),[])
// Expected output: [1,2,3,4]
This question already has answers here:
Convert string array to integer array
(4 answers)
Closed 4 years ago.
I need to take the first 1000 digits of pi as strings in an array and return them into a new array as digits:
from this: ["1","4","1","5","9","2"...] (the full array of numbers is already provided in my assignment)
to this: [1, 4, 1, 5, 9, 2...]
I've tried creating a new variable with an empty array and using the .join method but when I console log it it returns the an empty array.
const strNums = ["1","4","1","5","9","2"...]
const newArray = [];
const integers = strNums.join(newArray);
console.log(newArray);
const input = ["1","4","1","5","9","2"];
const output = input.map(Number);
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 4 years ago.
I have array1 that contains 1 char in each element.
What I need, is to get the value of array1[i].charCodeAt(); and put it in array2.
Easy to do it, with a for statement.
for(i=0;i<10;i++){
y[i]= x[i].charCodeAt();
}
I did some research but nothing that explain this case:
Is it possible to populate array2 by some sort of destructuring, or what I am asking is not supported in js? For example:
array1 =['a','b','c'];
array2 = [];
array2 = array1[].charCodeAt.
conole.log('The first char has code ' + array2[0]); // The first letter has code 97.
You aren't creating separate standalone variables, so destructuring isn't what you're looking for - but, you can use .map to transform the first array into the second:
const array1 =['a','b','c'];
const array2 = array1.map(char => char.charCodeAt(0));
console.log(array2);
You can use Array.prototype.map():
const array1 = ['a','b','c'];
const array2 = array1.map(c => c.charCodeAt());
console.log(array2);
This question already has answers here:
How to round all the values in an array to 2 decimal points
(4 answers)
How can I skip a specific Index in an array in a for loop javascript
(1 answer)
Closed 5 years ago.
Let's say there is this array of arrays:
theArray = [["name1", 12.23423, 54.243, 6.23566, 5675.552, ...],
["name2", 345.8655, 92.9316, ..],
["name3", 99.56756, 52.988, 3.09889, ...],
...
];
Each sub-array starts with a string and it is followed by numbers. My aim is to reduce the numbers to a shorter form.
I know that this can be done using .toFixed(2) in order to have only two digits after the dot by I don't know how to access them because of the string in the front.
I want them to remain as numbers because I must use them as data for a chart.
Do you have any suggestions?
You could keep the value of the first item.
var array = [["name1", 12.23423, 54.243, 6.23566, 5675.552], ["name2", 345.8655, 92.9316], ["name3", 99.56756, 52.988, 3.09889]],
result = array.map(a => a.map((v, i) => i ? +v.toFixed(2) : v));
console.log(result);
Simple solution by just using two nested for loops with Index 0 and Index 1.
theArray = [["name1", 12.23423, 54.243, 6.23566, 5675.552],
["name2", 345.8655, 92.9316],
["name3", 99.56756, 52.988, 3.09889],
];
for(var i=0;i<theArray.length;i++) {
for(var k=1;k<theArray[i].length;k++) {
theArray[i][k] = parseFloat(theArray[i][k].toFixed(2));
}
}
console.log(theArray);