Convert array to comma delimited string - javascript

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.

Related

How to convert an array of integers to a single digit

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);

JAVASCRIPT REGEX for digits suite

Is there a way to use regex to check if an array contains exactly one occurence of each number in a range ?
myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
I have tried this :
let regex = /[1-9]{1}/;
But this only checks that the array contains at least one occurence in the range : )
The described validation is not a particularly good use case for regex.
One alternative way to find the answer you seek is to:
Create a Set with the array items. (A Set by default only retains unique values.)
Convert the Set back to array.
Compare the lengths of the original array and the new array. If they mismatch, the difference is the number of array items that exist in duplicate.
// return TRUE if myArr only has unique values
[...new Set(myArr)].length === myArr.length
You can just filter for duplicates and compare the original array with the filtered to see if it had any duplicates. Upside here is that you can use the filtered array if you need it
let myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 5]
let uniques = myArr.filter((v, i, a) => a.indexOf(v) === i)
let hasDupes = myArr.length != uniques.length
console.log("hasdupes?", hasDupes);
console.log(uniques)

.map returns length of the resulting arrays for each iteration?

var king = [1,2,3,4];
var kong = [55,77];
var thor = king.map(function(num) { return num + 1 });
var pan = king.map(function(num) { return kong.push(num) });
console.log(kong); // [55, 77, 1, 2, 3, 4]
console.log(thor); // [2, 3, 4, 5]
console.log(pan); // [3, 4, 5, 6] ??
I thought I understood what .map was doing, but after playing around with it, I found a result that confused me. For the result of console.log(pan), I was expecting:
[[55, 77, 1], [55, 77, 1, 2], [55, 77, 1, 2, 3], [55, 77, 1, 2, 3, 4]]
However, the result is:
[3, 4, 5, 6]
It looks like it's returning the length of each resulting array? Confused.
From the MDN:
The push() method adds one or more elements to the end of an array and returns the new length of the array.
You have an array of lengths.
Here's an implementation of what you seem to want (not changing kong because it always feels better to be functional):
var pan = king.reduce(function(arr, num) {
arr.push((arr[arr.length-1]||kong).concat(num));
return arr
}, []);
You can use concat() instead.
var king = [1,2,3,4];
var kong = [55,77];
var pan = king.map(function(num) { return kong = kong.concat(num) });
console.log(pan);
push returns array length. So you have array of lengths.
You can achieve what you expect by:
var pan = king.map(function(num) {
kong.push(num);
return kong.slice(); // create array copy!
});
And do not forget to copy array, otherwise you will get an array with same array as elements.
Solution that is non destructive to kong
var king = [1, 2, 3, 4];
var kong = [55, 77];
var pan = king.map(function(_, i) {
return kong.concat(king.slice(0, i + 1));
});
console.log(pan);
map applys the function you specify to each of the elements in the array. So the answers it is giving you are correct for the first array
You don't need to manually push the elements inside a map. The map operation applies your function on every element of the array and returns a new array based on results.
To be honest that's the whole purpose of the map method.

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>");

Splice items from array considering indexes from another array

I have an array input and another array indexes. I want to remove item from array input whose index is provided in indexes array.
I have tried it using array.splice in for loop but as item is being removed in each iteration, indexes of other items are being changed.
JavaScript:
var array = [10, 11, 12, 13, 14, 15];
var indexes = [0, 1, 2, 3, 4, 5];
indexes.forEach(function(item) {
array.splice(item, 1);
});
console.log(array);
You can utilize Array.prototype.filter and do the following:
var array = [10, 11, 12, 13, 14, 15];
var indexes = [0, 1, 2, 3, 4, 5];
array = array.filter(function(x, i) {
return indexes.indexOf(i) === -1;
});
console.log(array);
Here you are using forEach loop which give you the item as first argument and the index on second one, so as per my understanding what you want to do can achieve by this, try this hope this solve your problem :)
indexes.forEach(function(item, index) {
array.splice(index, 1);
});
Sort the indexes array from high to low, then spice will only change the index of the numbers you have already removed

Categories

Resources