Concatenating Numbers in javascript [duplicate] - javascript

This question already has answers here:
Javascript Concatenate Array to String
(2 answers)
Closed 2 years ago.
My goal is to make numbers into strings.
If my actual = concatenateNumbers(7);
expected = "7"
My code for this would be:
function concatenateNumbers(num1) {
return num1.toString();
}
However, if my actual has 2 or 3 more values, actual = concatenateNumbers(7, 9) or actual = (7, 9 ,1) => the expected is = "79" or "791"
Can anybody give me an idea or hint on how I should approach this?

Use The arguments object converted to a real Array, and use Array.prototype.join() with an empty String:
function concatenateNumbers() {
return [...arguments].join("");
}
var numbersArrays = [
[],
[7],
[7, 9],
[7, 9, 1]
];
numbersArrays.forEach(numbersArray=>{
console.log(numbersArray.join(", ") + " => " + concatenateNumbers(...numbersArray));
});
console.log("1, 2, 3 => "+concatenateNumbers(1, 2, 3));
numbersArrays is just a convenient way to use SO's code snippet, along with "["+numbersArray.join(", ")+"]" to show each numbersArrays's Array as an Array, plus the actual call to the actual function concatenateNumbers.
Edited to make function's arguments actually a list of Numbers using the Spread syntax (...), as pointed out by VLAZ.
It will actually concatenate anything, the best it can...

Related

Is there any way to plus multi array number in javascript? [duplicate]

This question already has answers here:
How to calculate the sum of multiple arrays?
(6 answers)
Closed 1 year ago.
I have an array. With each item in array is an array number. And the length of each array is the same. For example:
var data = [[1,2,4,1], [2,2,1,3], [1,1,2,2], ...]
And the result I want to have:
=> res = [4, 5, 7, 6]
res is the result of adding arrays according to the corresponding index. And of course my data may also contain lots of items.
I have referenced through the lodash.unzipWith. But it doesn't seem viable. With any advice. please let me know. Sorry for my weak English
You can use reduce and write something like this, without lodash or anything
const data = [[1,2,4,1], [2,2,1,3], [1,1,2,2]]
const sumArrs = (arrs) => {
return arrs.reduce((prev, curr) => {
return curr.map((num, i) => num + (prev[i] || 0))
}, [])
}
console.log(sumArrs(data))

How to check if an item is already there in an array [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 2 years ago.
let us consider an array
let array=["a","b","c","d","a"]
a is already present in the array, how to return true/false for this condition.
i don't want to do this
let value=array.includes("a")
in this case i know a is repeated so i use includes("a"). How to write a generic solution to find if an item is repeated in an array .(imagine getting an array from an api, so u wont know what will be repeated )
Well you can use the .indexOf and .lastIndexOf to do that, so the idea is if both return the same index of the item then it's not repeated and it's unique but if the index is different then there are at least two copies of the item, so we can write a small function to do that given the array to search in and the item to search for
var x = [1, 6, 4, 6, 3, 2, 1];
function isRepeated(arr, n) {
return arr.indexOf(n) !== arr.lastIndexOf(n);
}
console.log("1 is repeated? " + isRepeated(x, 1));
console.log("3 is repeated? " + isRepeated(x, 3));
console.log("6 is repeated? " + isRepeated(x, 6));
console.log("4 is repeated? " + isRepeated(x, 4));

How to take digits of PI as strings and return an array of the digits as numbers? [duplicate]

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

Fastest way to fill an array with multiple value in JS. Can I pass a some pattern or function to method fill insted of a single value in JS? [duplicate]

This question already has answers here:
Does JavaScript have a method like "range()" to generate a range within the supplied bounds?
(88 answers)
Closed 4 years ago.
Is it any way to create an array a selected size(for example 10) and immediately on the spot fill in it with some numbers specified pattern (1, 2, 3, OR 2, 4, 6 and so on) in one statement in JS?
let arr = new Array(10).fill( (a) => {a = 1; return a++; } );
console.log(arr); // Should be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
In other words can I pass a some patern or function to method fill insted of a single value.
Actually there's much nicer idiom to create ranges: a spreaded Array constructor:
[...Array(n)]
creates an array of n undefined values. To get 0..n-1, just pick its keys:
[...Array(n).keys()]
for arbitrary ranges, feed it to map:
r = [...Array(10)].map((_, i) => i + 1)
console.log(r)
see here: Does JavaScript have a method like "range()" to generate an array based on supplied bounds?
old answer:
yep, you're looking for Array.from:
r = Array.from({length: 10}, (_, i) => i + 1);
console.log(r)
How does this work? .from inspects its first argument (which can be any object) and picks its .length property. Then, it iterates from 0 to length - 1 and invokes the second argument with two parameters - a value (which is undefined unless the first argument contains a corresponding numeric property) and an index, which takes values from 0...length-1. In this example, we have a function that just returns an index + 1, thus giving us 1..length.
Here's a useful wrapper for the above:
let range = (from, to) => Array.from({length: to - from + 1}, _ => from++);
console.log(range(1, 10))
For ES5, the idiom is Array.apply(null, {length:N}):
r = Array.apply(null, {length: 10}).map(function(_, i) {
return i + 1
})

parseInt misbehaves when passed as argument to a map call [duplicate]

This question already has answers here:
Why does parseInt yield NaN with Array#map?
(8 answers)
Closed 9 years ago.
Why is this happening?
var numbers = [ '1', '2', '3', '4' ];
var intNumbers = numbers.map( parseInt ); // intNumbers = [1, NaN, NaN, NaN]
var fltNumbers = numbers.map( parseFloat ); // fltNumbers = [1, 2, 3, 4, 5 ]
But Array.prototype.map.call( numbers, parseInt ); returns [ 1, 2, 3, 4];. I'm running this code in Google Chrome 26.0.1410.65.
The link to proper answer is given in comments, but i want to post it here
:
["1", "2", "3"].map(parseInt);
While one could expect [1, 2, 3]
The actual result is [1, NaN, NaN]
parseInt is often used with one argument, but takes two. The second
being the radix To the callback function, Array.prototype.map passes 3
arguments: the element, the index, the array
The third argument is ignored by parseInt, but not the second one, hence the possible confusion.
Quick fix
function returnInt(element){
return parseInt(element,10);
}
["1", "2", "3"].map(returnInt);
Actual result is an array of numbers (as expected)
https://developer.mozilla.org/en-GB/docs/JavaScript/Reference/Global_Objects/Array/map explains how map works.
I find it easier with the solution that jonah proposed, create a returning function for thing you want to map instead of tossing it..
intN = numbers.map(function(i) { return parseInt(i) });
The real reason is that you are trying to feed a function to map, but JS is not getting the function properly.
You better declare the function first and then feed it.
var titi = function(i) { return parseInt(i); };
var intN2 = numbers.map(titi);

Categories