How to convert an array of integers to a single digit - javascript

let's say I have got an array of [2, 4, 5, 6].
I want to be able to convert it to 2456.
Is there an easy and elegant way to do this in JavaScript?
I am aware of this question.

Using Array#join:
const arr = [2, 4, 5, 6];
const str = arr.join('');
console.log('string', str);
console.log('number', +str);

Related

How to access the last element of an array using destructuring? [duplicate]

This question already has answers here:
Destructuring to get the last element of an array in es6
(17 answers)
Get first and last elements in array, ES6 way [duplicate]
(1 answer)
Closed 8 months ago.
Suppose I have an array like this: [2, 4, 6, 8, 10].
I want to access the first and last element of this array using destructuring, currently I'm doing this:
const array = [2, 4, 6, 8, 10];
const [first, , , , last] = array;
console.log(first, last);
But this is only works with arrays of length 5 and is not generic enough.
In Python I could do something like this:
array = [2, 4, 6, 8, 10]
first, *mid, last = array
print(first, last)
But in JS this is not possible since rest elements should be the last. So, is there some way to do this in JS or this is not possible?
You can use object destructuring and grab the 0 key (which is the first element) and rename it to first & then using computed property names you can grab the array.length - 1 key (which is the last element) and rename it to last.
const array = [2, 4, 6, 8, 10];
const { 0: first, [array.length - 1]: last } = array;
console.log(first, last);
You can also grab the length via destructuring and then use that to grab the last element.
const array = [2, 4, 6, 8, 10];
const { length, 0: first, [length - 1]: last } = array;
console.log(first, last);
Another simple approach to access the last element would be to use the Array.prototype.at method. This is not related to destructuring but it's worth knowing.
const array = [2, 4, 6, 8, 10];
console.log(array.at(-1));
Not necessarily using destructuring, but still concise in my opinion:
const arr = [1, 2, 3, 4, 5];
const [ first, last ] = [ arr.at(0), arr.at(-1) ];
console.log(first, last);
No, you can't use destructuring like that without convoluted workarounds.
A shorter, more readable alternative is to just pop:
const array = [2, 4, 6, 8, 10];
const [first, ...middle] = array;
const last = middle.pop();
console.log(first, middle, last);
Or, just access them by index:
const array = [2, 4, 6, 8, 10];
const first = array[0];
const last = array[array.length - 1];
console.log(first, last);

Convert array to comma delimited string

I have the following array:
var ids = [1, 5, 28, 8];
I need to split the array into a string separated by a ,:
Example result: "1, 5, 28, 8"
Your example simply shows converting your array of numbers into an array of strings:
ids = [1, 5, 28, 8] to ids = "1","5","28","8"
That is done through a call to Array.map
var ids = [1, 5, 28, 8];
ids = ids.map(id => ''+id);
console.log(ids);
This converts each number in the array into a string in the array.
If you want your array of numbers to be converted into a single string like this:
ids = [1, 5, 28, 8] to ids = "1,5,28,8"
Then you simply need to use Array.join
var ids = [1, 5, 28, 8];
ids = ids.join(',');
console.log(ids);
This creates a single strings that separates each array entry with a comma.
Use map function to map each element to quoted string, then join all elements to single string.
[1, 5, 28, 8].map(x => `"${x}"`).join(",")
With join
var ids = [1, 5, 28, 8];
let string ids.join(',');
console.log(string);
Output
"1, 5, 28, 8"
You can also use the reduce function:
[1,2,3,4,5].reduce( (sum,val) => sum + ',' + val );
Output:
"1,2,3,4,5"
If you dont provide an initial value to the reduce function then it just uses the first value in the array as the sum, and starts reducing from the second value onwards.

How to combine array within another array using javascript or jquery?

I have an array named arr and within that array, I have another array.My question is, how to combine this two array?
var arr=["1","2","[3,4]","5"]
My output should be like this:
1,2,3,4,5
Thanks in advance!
You could use spread syntax ... with map and JSON.parse methods.
var arr = ["1","2","[3,4]","5"]
var result = [].concat(...arr.map(e => JSON.parse(e)))
console.log(...result)
Considering that you have an actual array and not a string you can flatten like this
var arr=["1","2",["3","4"],"5"]
var flat = [].concat(...arr)
console.log(flat)
You can change it to string and further replace the square brackets using replace(/[\[|\]]/g,''):
var arr=["1","2","[3,4]","5"];
var res = arr.toString().replace(/[\[|\]]/g,'');
console.log(res);
If the question is how to flat an array like this [1,2,[3,4],5] or this [1,[2,[[3,4],5]]] into this[ 1, 2, 3, 4, 5 ] here a pretty general and short solution:
var arr = [1, [2, [[3, 4], 5]]];
var newArr = JSON.parse("[" + JSON.stringify(arr).replace(/\[|\]/g, "") + "]");
console.log(newArr)
Or .flat if browser supports it:
var arr = [1, 2, [3, 4, [5, 6]]];
arr.flat();
console.log(arr)

what does max() function do in javascript if array has several equally large numbers

If we get something like
array=[5,5,5,5,3,2];
return Math.max.Apply(Math,array);
How do I get it to return the numbers from first to last if such a case occurs.
To answer the question in the title:
what does max() function do in javascript if array has several equally
large numbers
The answer is, nothing. Math.max() doesn't act on arrays.
You can pass an array by spreading the items as arguments to max():
Math.max(...[1,2,3]) // 3
Or as you've seen, with apply():
Math.max.apply(Math, [1,2,3]) // 3
If the question is more:
What does Math.max() do when more than one of the same maximum number is given?
The answer is, it returns that number:
const a = [5, 5, 5, 5, 3, 2]
const max = Math.max(...a)
console.log(max) // 5
This question is confusing:
How do I get it to return the numbers from first to last if such a case occurs.
You want it to return a sorted array? From [5, 5, 5, 5, 3, 2] to [2, 3, 5, 5, 5, 5]?
a.sort() // [2, 3, 5, 5, 5, 5]
You want dupes removed? From [5, 5, 5, 5, 3, 2] to [2, 3, 5]?
Array.from(new Set(a)) // [2, 3, 5]
Could you clarify your question?
The best way to do this is the following:
var a = [5,5,5,5,3,2];
var largest = Math.max.apply(null,a)
var filtered = a.filter(function(item) {
item === largest
});
Where filtered will have contain all the largest elements.
In #Clarkie's example, he's calling Math.max more frequently than needed.
In both Dan and Clarkie's example they're capitalizing Apply which is incorrect, the correct function to call is Math.max.apply and Math need not be passed in as the first argument.
See the following for a working example:
https://jsfiddle.net/fx5ut2mm/
Modifying #Clarkie's very nice idea. We can boil it down to...
var a = [5,5,5,5,3,2],
m = Math.max(...a),
f = a.filter(e => e == m);
document.write("<pre>" + JSON.stringify(f) + "</pre>");

Convert string containing arrays to actual arrays [duplicate]

This question already has answers here:
Convert string with commas to array
(18 answers)
Closed 7 years ago.
I have no idea why I'm having so much trouble with this. This seems like it should be really simple.
I have a JavaScript string like the following:
var str = '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]';
I actually want to convert this into an array of arrays. str.split(',') doesn't work because it'll split on the commas in the inner arrays.
I'm sure this conversion is probably something stupidly simple, but I must be missing it. Any help would be appreciated.
The string str confirms to the JSON spec, so it can be parsed with JSON.parse.
var arr = JSON.parse(str);
var str = '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]';
var arr = JSON.parse("[" + str + "]");
console.log(arr[0][0]); // [1, 2, 3]
console.log(arr[0][0][0]); // 1
You may use JSON.parse, more info here
https://jsfiddle.net/5yz95ktg/

Categories

Resources