This question already has answers here:
JavaScript "new Array(n)" and "Array.prototype.map" weirdness
(14 answers)
How to create an array containing 1...N
(77 answers)
Closed 2 years ago.
I am trying to create an Array using new Array() and filling with index + 1 but somehow, though array is creating successfully but values are not filling correctly.
Code -
var aa = (new Array(4)).map((x, index) => {
return index + 1;
});
console.log(aa);
Output - [undefined, undefined, undefined, undefined]
Expected - [1, 2, 3, 4]
Let me know what I am doing wrong here.
map only visits entries that actually exist, it skips gaps in sparse arrays.
There are various ways to do this:
You can use Array.from and its mapping callback:
const as = Array.from(Array(4), (_, index) => index + 1);
console.log(as);
You can use a simple for loop:
const as = [];
for (let index = 1; index <= 4; ++index) {
as.push(index);
}
console.log(as);
You can use fill and then map:
const as = Array(4).fill().map((_, index) => index + 1);
console.log(as);
A variant of fill+map, you can use spread as Igor shows.
[...Array(4)].map((v, i) => i + 1)
Related
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 8 months ago.
I was trying to get an array with some arrays inside of it, and each of those inner arrays should contain ONE of the n powers of 2, not all.
let n = 5;
let arr = Array(n + 1).fill([]);
const transform = function (el, i) {
el.push(2 ** i);
};
console.log(arr); // [Array(0), Array(0), Array(0), Array(0), Array(0), Array(0)]
arr.map(transform);
console.log(arr); //[Array(6), Array(6), Array(6), Array(6), Array(6), Array(6)]
//was expecting //[[1], [2], [4], [8], [16], [32]]
Fill is just setting every index with a reference to that array. It is not creating a new array in every index.
The easiest way to create an array and fill it with empty arrays is with Array.from
const n = 5;
const transform = (arr, index) => arr.push(2 ** index);
const myArray = Array.from({length: n}, () => []);
myArray.forEach(transform);
console.log(myArray);
When using fill, they share the same instance. So changing one changes all the others. You need to use map after filling
new Array(6).fill(null).map(() => []).map(transform)
It may be easier to use a traditional for loop to accomplish your end result. Using map and transform is a more roundabout way of doing the following:
let n = 5;
let arr = [];
for (let i = 0; i <= n; i++) {
arr.push([2**i]);
}
console.log(arr);
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))
This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 5 years ago.
how to delete the duplicate value from the array.
var list =[1,1,5,5,4,9]
my result will be
var list =[4,9]
how can I do by using lodash
You could check the index and last index of the actual value.
var list = [1, 1, 5, 5, 4, 9],
result = list.filter((v, _, a) => a.indexOf(v) === a.lastIndexOf(v));
console.log(result);
You can do
var list =[1,1,5,5,4,9];
let result = list.reduce((a, b) =>{
a[b] = a[b] || 0;
a[b]++;
return a;
}, []).map((e, idx) => e==1? idx: undefined).filter(e => e);
console.log(result);
you could use _.uniqBy()
_.uniqBy(list ,function(m){
return list.indexOf(m) === list.lastIndexOf(m)
})
This question already has answers here:
How to get first N number of elements from an array
(14 answers)
Closed 5 years ago.
i would like to get the first 3 elements of an array of variable length. i've sorted my array and i would like to get a Top 3.
here's what i've done :
var diffSplice = this.users.length - 1;
return this.users.sort(this.triDec).splice(0,diffSplice)
my "solution" work only for an array of 4 element ( -1 )
Is there a better way to use the splice method ?
Thanks for your help
You could use Array#slice for the first three items.
return this.users.sort(this.triDec).slice(0, 3);
Don't you want to use a const value for diffSplice like
var diffSplice = 3;
return this.users.sort(this.triDec).slice(0,diffSplice)
try running
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(0, 3));
refer to Array Silce
Fill out the deletecount for Splice:
var sortedArray = this.users.sort(this.triDec);
return sortedArray.splice(0, 3);
check MDN
This question already has answers here:
Summing ; delimited values in Javascript
(1 answer)
How to sum elements at the same index in array of arrays into a single array?
(7 answers)
Closed 5 years ago.
I am trying to add together an undetermined amount of arrays, but only add or reduce them item by item.
I cannot figure out how to make this work in ES6 javascript.
const arrayList = [
[1, 2, 3],
[1, 2, 3],
[2, 2, 2]
];
const totalRow = arrayList.map((array) => {
const total = [];
array.map((number, i) => {
total[i] = (total[i] == undefined ? 0 : total[i]) + number;
});
return total;
});
//Output is just 3 more arrays with no change, as it seems
//the total variable resets to an empty array with each iteration.
//what i want is this output:
[4, 6, 8]
What am I doing wrong? I tried reduce method as well but came up empty