Convert string into array of int [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I want to convert "1,2,3" to [1,2,3].
But there is an exception when converting "" to array. Because I get [""]. That is not valid for my case. So I need to check is it number or String. Let see this in code
function someWayToParse(some_string) {
var final_product = [];
var tmp_array = some_string.split(',');
//if some_string == "" tmp_array will result [""];
if (tmp_array[0].length===0)
return [];
for (var item in tmp_array)
final_product.push(parseInt(tmp_array[item], 10));
return final_product;
}
var stringToParse = "1,2,3";
var array_of_ints = someWayToParse(stringToParse);
I am just looking the best way to do this in a function and avoid possible mistakes.
Please be memory efficient, for my curiosity's sake.

Smaller code for it would be:
function myConverter(string) {
if (!string) return [];
return string.split(',').map(Number);
}
console.log(myConverter('1,2,3'));

Related

Multi-push vs. multi-map [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 days ago.
The community is reviewing whether to reopen this question as of 4 days ago.
Improve this question
I'm asked to get attributes collection out of an array object,
let a = [
{name:'aname',age:21},
{name:'bname',age:22},
{name:'cname',age:23},
{name:'dname',age:24},
{name:'ename',age:25},
{name:'fname',age:26},
{name:'gname',age:27}]
// wanted
let ok = {
names:'aname;bname;cname;dname;ename;fname;gname',
ages:'21;22;23;24;25;26;27'
}
and I got 2 ways of doing it:
alpha just using map of an array:
// alpha
let res = {
names:'',
ages:''
}
res.names=a.map(iter=>iter.name).join(';')
res.ages=a.map(iter=>iter.age).join(';')
//then return res
// ========================================================
and beta just iterate the array and append each attribute in the tabulation array:
// beta
let res = {
names:[],
ages:[]
}
a.forEach(iter=>{
res.names.push(iter.name)
res.ages.push(iter.age)
})
// then handle res's fields
ok.names = res.names.join(';')
ok.ages = res.ages.join(';')
so which way should I use to get the collection? Will alpha get slower or faster than beta when the objects in a get lots of fields(attrs)?
Both approaches are good. I'd say it depends on your personal preference what you'd want to use.
However, It seems to me that if you are aiming for performance, the following would yield better results.
let a = [
{name:'aname',age:21},
{name:'bname',age:22},
{name:'cname',age:23},
{name:'dname',age:24},
{name:'ename',age:25},
{name:'fname',age:26},
{name:'gname',age:27}]
let ok = { names: '', ages: ''}
for (let i = 0; i < a.length; i++){
const iter = a[i]
ok.names += iter.name + ";";
ok.ages += iter.age + ";";
}
ok.names = ok.names.slice(0,-1)
ok.ages = ok.ages.slice(0,-1)
console.log(ok)
This apporach eliminates the need to create new arrays or joining them (join is a heavy operation). Just create the string you want and at the end of it all, remove the one extra semicolon.
I consider that alfa is simpler and clearer for me, but I guess it is up to you...

Difficult to find smallest e biggest number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
im trying to Find the Smallest and Biggest Numbers. i can do this in for > let. but when i try to put this in a function it does not work.
const myNumbers = [1111, 245, 535 ,222, 221,12,233444];
function findnum(){
for (let i=0; i < myNumbers.length ; i++ ){
const smallNum = Math.min(...myNumbers)
const bigNum = Math.max(...myNumbers)
break
}
}
result = findnum(smallNum,bigNum)
console.log(result)
If you pass two variables to a function like this result = findnum(smallNum, bigNum), then you should have the function's signature with two arguments, like this:
function findnum(smallNum, bigNum){
Pay attention that smallNum and bigNum only exist inside the function. As #pilchard mentioned, in your code you don't need arguments, the loop is unnecessary, and the function needs a return.
This should work.
const myNumbers = [1111, 245, 535 ,222, 221, 12, 233444];
function findnum(){
const smallNum = Math.min(...myNumbers)
const bigNum = Math.max(...myNumbers)
return [smallNum, bigNum]
}
result = findnum()
console.log(result)

How to check the array is of how many dimension in javascript? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
For example I have an array as follows & expected output is given.
In javascript how can we determine dynamically how many levels are there in my array ary.
var ary = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]];
Output: 3
var ary = ["a","b",["c","d"],"e",["f","g","i"]];
Output: 2
var ary = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
Output: 4
Here is a reccursive function that will traverse through the depths of the array and track the maximum of it. Note that the tracking is done via properties attach to the function itself.
var ary1 = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
function getDimension(arr, start) {
//Attach depth tracking properties to the function
if (start){
getDimension.depth = 0;
getDimension.maxDepth = 0;
}
//Track max depth
getDimension.depth++
if (getDimension.depth > getDimension.maxDepth)
getDimension.maxDepth++;
//Manage recursion
for (let element of arr)
if (element instanceof Array)
getDimension(element);
getDimension.depth--;
//In first level at this point
if (getDimension.depth === 0)
return getDimension.maxDepth;
}
let d = getDimension(ary1, true);
console.log(d);

remove quotes from javascript array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a javascript with the unixtimestamp and the price of an item at that particular time. The timestamp is coming in string as listed below. How do I remove the double quotes from the timestamp. This is the array. I used the string replace function but not working.
["1356998400000", 222.69179362385]
["1357084800000", 209.18952317885]
["1357171200000", 211.95012017103]
["1357257600000", 200.15913266219]
["1357344000000", 215.58462758679]
var arr = [["1356998400000", 222.69179362385],
["1357084800000", 209.18952317885],
["1357171200000", 211.95012017103],
["1357257600000", 200.15913266219],
["1357344000000", 215.58462758679]];
arr.forEach(function(item){
item[0] = Number(item[0])
})
console.log(arr);
Just Use Number() to make a string containing number to number.
Something like this?
var myArr = ["1356998400000", 222.69179362385,
"1357084800000", 209.18952317885,
"1357171200000", 211.95012017103,
"1357257600000", 200.15913266219,
"1357344000000", 215.58462758679];
//check the values in the array before making changes
console.log(myArr);
var i;
for(i = 0; i < myArr.length; i++) {
if(typeof myArr[i] == "string") {
myArr[i] = parseFloat(myArr[i]);
}
}
//check the value of the array after changes
console.log(myArr);

Array.lenght returns undefined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I wish to get the length of an array so I can use it further in another function but it returns undefined. This piece of code gets a file, opens it and splits it for each new line. I'm trying to get the length of the array but returns undefined.
function readBatFile(bfile){
var rawFile1 = new XMLHttpRequest();
rawFile1.open("GET", bfile, false);
rawFile1.onreadystatechange = function ()
{
if(rawFile1.readyState === 4)
{
if(rawFile1.status === 200 || rawFile.status === 0)
{
var allCode = rawFile1.responseText;
var ary = new Array;
ary = allCode.split(/.*\n/gm);
var rcount = ary.lenght;
document.getElementById('test').innerHTML = rcount;
}
}
};
rawFile1.send(null);
}
It is spelled length not lenght.
It should be:
var rcount = ary.length;

Categories