I have an array:
["1", "2","3","4","5"]
that I would like to change to:
[["1, 0 ,0 ,0"], ["2, 0, 0, 0"],["3,0,0,0"],["4,0,0,0"],["5,0,0,0"]]
I've tried to achieve this with the following code:
var arr1 = ["1", "2","3","4","5"];
var arr2 = [,"0", "0","0"];
for(var z=0; z<arr1.length; z++)
{
arr1[z] = arr1[z].concat(arr2);
console.log(arr1)
}
However, this doesn't achieve what I want and places commas between each item, which I think is because it is not a string? I've tried using .join too but I couldn't get that to work either.
Could someone point me in the right direction for this please? Thanks.
You first need to convert each element to array and then append the second array to the newly converted array element. The following code snippet would make it clear -
var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
for (var z = 0; z < arr1.length; z++) {
// First convert the element into a list
arr1[z] = [arr1[z]];
// Then append the second array to it
arr1[z] = arr1[z].concat(arr2);
// Another way -
//arr1[z].push(...arr2);
}
// Final array -
console.log(arr1);
Using Map() :
Another way to do it would be using map() as below -
var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
arr1 = arr1.map(el=>[el,...arr2]);
console.log(arr1);
Using ForEach()
You could also do it using forEach() method -
var arr1 = ["1", "2", "3", "4", "5"];
var arr2 = [ "0", "0", "0"];
// this will note mutate original arr1 and store result in res
let res = [];
// ... is the spread operator which will allows iterable objects to be expanded in place
arr1.forEach(el=>res.push([el,...arr2]));
// final result
console.log(res);
There's probably numerous other ways as well... These were just few I have listed. You could even do it using naive nested loops method if you don't know anything about map(), forEach(), or concat() / push() methods.
Hope this helps !
Please try the following example
const array = ["1", "2", "3", "4", "5"];
const output = array.map((entry) => [`${entry}, 0, 0, 0`]);
console.log(output);
See
Array.prototype.map()
Template literals (Template strings)
if it's set in stone, you can do
let arr = []
var arr1 = ["1", "2","3","4","5"];
var arr2 = ["0", "0","0"];
arr1.forEach(el=>arr.push([el, ...arr2]));
console.log(arr)
Use map to go through each of your element and append the array with zeros, transform it to a string and wrap in an array again which will hold one value
const a = ["1", "2", "3", "4", "5"]
const arr = [0, 0, 0, 0];
const res = a.map(x => [
[x, ...arr].join()
])
console.log(res)
I am trying to change a specific key's value in json as below :
input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}]
output= [{"201708":10,"201709": 12, "metric":"managedAttrition"},{"201708":10,"201709": 12, "metric":"unmanagedAttrition"},{"201708":10,"201709": 12, "metric":"EndingHeadcount"}]
i have tried looping in the input like input.forEach(element =>{//code})but somewhere iam missing.
This not works??
let input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}]
input.forEach(i=>{
i.metric = 'abc'
})
input.forEach(i=>{
alert(i.metric)
})
I have used spread operator:
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
example:
var a = [1,2,3]
var b = [4,5,6]
a.push(...b)
a //which is [1,2,3,4,5,6]
input = [{"201708":10,"201709": 12, "metric":"attritionManaged"},{"201708":10,"201709": 12, "metric":"attritionUnManaged"},{"201708":10,"201709": 12, "metric":"EHC"}]
var output = input;
output.forEach(function(currentValue, index, arr){
currentValue.metric = getString(currentValue.metric);
})
function getString(str){
var arr = [];
var arr1 = [];
var isUpperArrived = 0;
if(str.length>0)
{
arr.push(str[0].toUpperCase());
}
for(var i=1;i<str.length;i++)
{
if(str[i]==str[i].toUpperCase())
{
isUpperArrived=1;
arr1.push(str[i].toLowerCase());
}else{
if(!isUpperArrived)
{
arr.push(str[i]);
}else{
arr1.push(str[i]);
}
}
}
//pushing arr using spread operator
arr1.push(...arr);
return arr1.join('');
}
console.log(output);
Is there an easy way to create an array of empty strings in javascript? Currently the only way I can think to do it is with a loop:
var empty = new Array(someLength);
for(var i=0;i<empty.length;i++){
empty[i] = '';
}
but I'm wondering if there is some way to do this in one line using either regular javascript or coffeescript.
Update: on newer browsers - use .fill: Array(1000).fill('') will create an array of 1000 empty strings.
Yes, there is a way:
var n = 1000;
Array(n).join(".").split("."); // now contains n empty strings.
I'd probably use the loop though, it conveys intent clearer.
function repeat(num,whatTo){
var arr = [];
for(var i=0;i<num;i++){
arr.push(whatTo);
}
return arr;
}
That way, it's perfectly clear what's being done and you can reuse it.
You can get an array defining the size and fill it with some tokens:
const arr = Array(size).fill("");
here's a simpler way using generic protos on Array and String:
"".split.call(Array(1001), ",")
EDIT: There's now even simpler ways, some of which are readable:
Array(1000).fill("");
" ".repeat(999).split(" ");
You can try to do it by this way:
let n = 1000;
var emptyStrings = [...Array(n)].map(() => '')
Using Array.from;
const n = 5;
const arr = Array.from({length: n}).map(el => "")
console.log(arr)
You could make a function out of it:
function stringArray(length) {
var arr = [];
for(var i = 0; i < length; ++i) { arr.push(''); }
return arr;
}
You could do something like this:
var someLength = 10;
var empty = Array.apply(0, Array(someLength)).map(function(){return '';});
// result: ["", "", "", "", "", "", "", "", "", ""]
Just for fun
var empty = Array.apply(null, new Array(someLength)).map(String.prototype.valueOf,"");
The easiest thing to do in CoffeeScript is to use a loop comprehension:
a = ('' for i in [0 ... someLength]) # Note: 3 dots
a = ('' for i in [1 .. someLength]) # Or 2 dots and start at 1
#...
Demo: http://jsfiddle.net/ambiguous/b9Vj9/
Although not widely available, once browsers start supporting EcmaScript 6 array comprehensions, you will be able to do something along the lines of:
var n = 1000;
var empty_strs = ['' for (x of new Array(n))]
Easy enough.
Array with a length of 10 items, filled with empty strings (""):
Array.from({length: 10}).map( _ => "" );
// Array(10) [ "", "", "", "", "", "", "", "", "", "" ]
Array with a length of 10 items, filled with numbers from 0 to 9:
Array.from({length: 10}).map( (_, index) => index );
// Array(10) [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Array with a length of 10 items, filled with numbers from 1 to 10:
Array.from({length: 10}).map( (_, index) => index + 1 );
// Array(10) [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Array with a length of 10 items, filled with string containing "Chapter (1 ... 10).":
Array.from({length: 10}).map( (_, index) => `Chapter ${index + 1}.` );
// Array(10) [ "Chapter 1.", "Chapter 2.", "Chapter 3.", ... ]
(Using _ here as we don't use the value anyway.)
I have below string -
var a = "1,2,3,4";
when I do -
var b = a.split(',');
I get b as ["1", "2", "3", "4"]
can I do something to get b as [1, 2, 3, 4] ?
You can use Array.map to convert each element into a number.
var a = "1,2,3,4";
var b = a.split(',').map(function(item) {
return parseInt(item, 10);
});
Check the Docs
Or more elegantly as pointed out by User: thg435
var b = a.split(',').map(Number);
Where Number() would do the rest:check here
Note: For older browsers that don't support map, you can add an implementation yourself like:
Array.prototype.map = Array.prototype.map || function(_x) {
for(var o=[], i=0; i<this.length; i++) {
o[i] = _x(this[i]);
}
return o;
};
My 2 cents for golfers:
b="1,2,3,4".split`,`.map(x=>+x)
backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(','). The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x (which is even shorter than the Number function (5 chars instead of 6)) is equivalent to :
function(x){return parseInt(x,10)}// version from techfoobar
(x)=>{return parseInt(x)} // lambda are shorter and parseInt default is 10
(x)=>{return +x} // diff. with parseInt in SO but + is better in this case
x=>+x // no multiple args, just 1 function call
I hope it is a bit more clear.
This is very simple.Such as:
["1", "2", "3", "4"].map(i=>Number(i))
you can run the demo.
let result = ["1", "2", "3", "4"].map(i=>Number(i));
console.log(result);
Array.from() for details go to MDN
let a = "1,2,3,4";
let b = Array.from(a.split(','),Number);
or
let c = ["1", "2", "3", "4"].map(Number);
b and c is an array of numbers.
demonstration:
let a = "1,2,3,4";
let b = Array.from(a.split(','),Number);
let c = ["1", "2", "3", "4"].map(Number);
console.log(`b: ${b}, c: ${c}`);
Map it to integers:
a.split(',').map(function(i){
return parseInt(i, 10);
})
map looks at every array item, passes it to the function provided and returns an array with the return values of that function. map isn't available in old browsers, but most libraries like jQuery or underscore include a cross-browser version.
Or, if you prefer loops:
var res = a.split(",");
for (var i=0; i<res.length; i++)
{
res[i] = parseInt(res[i], 10);
}
+string will try to change the string to a number. Then use Array.map function to change every element.
"1,2,3,4".split(',').map(function(el){ return +el;});
A more shorter solution: map and pass the arguments to Number:
var a = "1,2,3,4";
var b = a.split(',');
console.log(b);
var c = b.map(Number);
console.log(c);
One liner
Array.from(a.split(','), Number)
There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.
Reasons:
It's working:
var src = "1,2,5,4,3";
var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
var obj = {1: ..., 3: ..., 4: ..., 7: ...};
var keys= Object.keys(obj); // ["1", "3", "4", "7"]
var ids = keys.map(parseFloat); // [1, 3, 4, 7]
var arr = ["1", 5, "7", 11];
var ints= arr.map(parseFloat); // [1, 5, 7, 11]
ints[1] === "5" // false
ints[1] === 5 // true
ints[2] === "7" // false
ints[2] === 7 // true
It's shorter.
It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:
// execution time measure function
// keep it simple, yeah?
> var f = (function (arr, c, n, m) {
var i,t,m,s=n();
for(i=0;i++<c;)t=arr.map(m);
return n()-s
}).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
> f(Number) // first launch, just warming-up cache
> 3971 // nice =)
> f(Number)
> 3964 // still the same
> f(function(e){return+e})
> 5132 // yup, just little bit slower
> f(function(e){return+e})
> 5112 // second run... and ok.
> f(parseFloat)
> 3727 // little bit quicker than .map(Number)
> f(parseFloat)
> 3737 // all ok
> f(function(e){return parseInt(e,10)})
> 21852 // awww, how adorable...
> f(function(e){return parseInt(e)})
> 22928 // maybe, without '10'?.. nope.
> f(function(e){return parseInt(e)})
> 22769 // second run... and nothing changes.
> f(Number)
> 3873 // and again
> f(parseFloat)
> 3583 // and again
> f(function(e){return+e})
> 4967 // and again
> f(function(e){return parseInt(e,10)})
> 21649 // dammit 'parseInt'! >_<
Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt
As a variant you can use combiantion _.map and _.ary methods from the lodash library. Whole transformation will be a more compact. Here is example from the official documentation:
_.map(['6', '8', '10'], _.ary(parseInt, 1));
// → [6, 8, 10]
Use Array.from for this, Try this:
let b = ["1", "2", "3", "4"];
b = Array.from(b,Number);
console.log(b);
The underscore js way -
var a = "1,2,3,4",
b = a.split(',');
//remove falsy/empty values from array after split
b = _.compact(b);
//then Convert array of string values into Integer
b = _.map(b, Number);
console.log('Log String to Int conversion #b =', b);
Matt Zeunert's version with use arraw function (ES6)
const nums = a.split(',').map(x => parseInt(x, 10));
This works amazing if you need to convert an array of strings to numbers.
const numbers = arr => arr.map(Number);
numbers(['1', '2', '3','4']); // [1, 2, 3, 4]
Since all the answers allow NaN to be included, I thought I'd add that if you want to quickly cast an array of mixed values to numbers you can do.
var a = "1,2,3,4,foo,bar";
var b = a.split(',');
var result = b.map(_=>_|0) // Floors the number (32-bit signed integer) so this wont work if you need all 64 bits.
// or b.map(_=>_||0) if you know your array is just numbers but may include NaN.
You can use JSON.parse, adding brakets to format Array
const a = "1,2,3,4";
const myArray = JSON.parse(`[${a}]`)
console.log(myArray)
console.info('pos 2 = ', myArray[2])
You can transform array of strings to array of numbers in one line:
const arrayOfNumbers = arrayOfStrings.map(e => +e);
let ar = [ '682', '874', '906', '11168', '73714',
'74377', '74034', '138860', '138891', '139161', '139562',
'139733', '139560', '74049', '139759', '139934', '140104',
'141335', '141356', '141334', '141337', '141360', '141358',
'141365', '141419', '143333', '151477', '147342', '141355',
'167847', '192141', '196760', '191687', '197351', '197055',
'198852', '198731', '198816', '199034', '200053', '199226',
'217818', '200055', '222039', '230533', '230530', '231127',
'222042', '231100', '236171', '236913', '236980', '237015',
'237016', '237052', '237551', '237560', '237590', '237637',
'237733', '237731', '237655', '238890', '238910', '238837',
'238926', '238972', '238925', '239755', '239696', '239898',
'240037', '239909', '240036', '240082', '240097', '240526',
'240770', '678151', '678950', '678985'];
let arry=[]
ar.map(arr=>{
arry.push(parseInt(arr))
});
console.log(arry);