i am trying to solve a code challenge that asks me to fill an array with the value passed as an argument in a function.
For example = fizzBuzz(10)
should return an Array with 10 slots and for each slot increment 1
[0, 1, 2, 3 ,4, 5, 6, 7, 8, 9, 10]
i have tried with a loop and with the fill method but i am having difficulties on this.
This is the first step of the algorithm. Can someone help me ?
Here is my last attempt:
function fizzbuzz(n) {
// Write your code here
const array = new Array(n)
for(let i = 0; i < n; i++) {
array.fill(n, 0))
}
return array
}
This wont work cause the fill method is only called once for every slot i guess. Can someone help me ?
I have tried with the forEach method, fill method and with a loop, but i am unable to solve the first step of this algorithm.
I need nelp solving the first step of this algorithm.
So: you are learning to use arrays.
Let's start with the basics.
An array is a kind of variable that points to a list of things.
Javascript simulates traditional arrays by numbering each element:
const array = new Array(10);
But javascript is not vary rigid about how many elements are in an array, so you could also say:
const array = [];
There's a difference between these two, even though absolutely nothing is in it yet: the first form has 10 undefined values. The second form as no values and a length of 0. But they both work just fine.
How do you access elements in this list? By number!
console.log(array[0]);
In both of the above cases, you are going to get "undefined" as a result.
Now to understand your homework, all you need to know is how to assign values to the array. The array object method "fill" is no good, because what your initial loop does is assign ALL elements to 0, and then to 1, and then to 2, etc. That's no good. Who knows why we even have a "fill" method. I've never used it in my life.
But what happens ALL THE TIME is:
const array = [];
for (let i=0; i < n; i++) {
array[i] = i;
}
What is happening here?
The element in the list at position 0 is set to 0.
The element in the list at position 1 is set to 1.
And so on.
Because it is javascript, there are actually MANY ways to do this. This is just one. Using "fill" is not one. But this is the most fundamental pattern common across most languages, so it is a good one to master before moving on to fancier approaches.
If you are trying to created an Array of size N with values from 0...N then the size of the array should be N + 1.
For initializing the array
You can use ES6 using Array
keys() and spread operator.
const N = 10;
const array = [...Array(N+1).keys()]
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
If you want to use for loop, then you can populate the array like this:
const N = 10;
const array = new Array(N+1);
for(let i=0; i<array.length; i++) {
array[i] = i;
}
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
How to create an array containing 1...N
const data = response.data
console.log(data)
const temp = data.ssps_with_scated.splice(5, 1)(1, 3)[0]
data.ps_with_ed.splice(2, 1, 0, temp)
i am trying to achieve finally i got it. But issue is, i cant expect the array value same all the time. So i have decided to re-arrange the array values based on the ID.
Well,
splice(7,1)(21,3)
This code will cause an error. Since Array.prototpy.slice returns a new array.
It would be the same if you would do this:
const a = [1,2,3]
const b = a.splice(1,1);
b(2,1) // b.splice(...) is not a function
EDITED:
Maybe there is a faster/better solution but...
You can make it more general but for your case only:
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21];
const first = array[7];
const second = array[21];
// Add elements on certain indices in array (second and third)
array.splice(2, 0, first, second)
// Remove first from the array (index is 7 + 2 because we added 2 elements)
array.splice(9, 1)
// Remove 21 from the array (index is 22 - 1 because we added 2 elements and removed 1, not: number 21 is on index 22)
array.splice(21, 1);
data shouldn't be a const since the value is getting updated. Splice can also only be called on one array at a time. If you need to call it on multiple arrays, create a loop or iterate over them.
If you want to inject the current value of the 7th position into the 2nd position... you'd need to do something like...
array.splice(2, 0, array[7])
Please help, I've been looking for an answer for far too long.
I'm trying to create an array using push method to insert the numbers
0 to 10 into positions 0 through 10 of the numbers array you just initialized above.
I did this:
var numbers = [];
for(var i = 0; i < 10; i++) {
numbers.push(i);
console.log(numbers);
And got this result, which I think is correct but not 100% sure:
[ 0 ]
[ 0, 1 ]
[ 0, 1, 2 ]
[ 0, 1, 2, 3 ]
[ 0, 1, 2, 3, 4 ]
[ 0, 1, 2, 3, 4, 5 ]
[ 0, 1, 2, 3, 4, 5, 6 ]
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
0
Then I am to test the array push method by printing the sum of the values at
position 3 and 6 of the array (use the console.log() function to print to the console).
The outputted value should be 9.
I am so stuck on this point and cannot find a sample anywhere of how to accomplish this. I thought it might be something like:
console.log(numbers(sum[3, 6]);
If you want to have a sum() function, then try the following:
function sum(x, y) {
return x + y;
}
console.log(sum(numbers[3], numbers[6]));
Here's a Fiddle: https://jsfiddle.net/7181h1ok/
To sum the values of two indices of an array, you use the + addition operator in the following fashion:
var numbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
var sum = numbers[3] + numbers[6]; //adds the value in index 3 of the numbers array to the value in index 6 of the numbers array.
console.log(sum); //prints the sum to the console.
As a note, if you are unfamiliar with JavaScript and/or its operators, there's useful documentation at w3schools that can get you started.
First, let's convert your code to a little bit better style:
const numbers = [];
for (let i = 0; i < 10; i++) {
numbers.push(i);
console.log(numbers);
}
Note: I made numbers a const instead of a var, since you don't change it. I also made i a let binding instead of a var. In general, var is a legacy and should never be used. Use const instead if at all possible, otherwise use let.
Also, I inserted a space after the for keyword. It is generally recommended to separate the parentheses which enclose the header of a control structure keyword (if, while, for, etc.) with a space, to make it visually distinct from the parentheses for the argument list of a function call, which has no space.
Secondly: Your result is not correct. (Hint: how many numbers are the numbers 0 to 10?) It should include the numbers 0 to 10, but it only includes the numbers 0 to 9. You have what is generally called an off-by-one-error. These errors are very common when dealing with trying to manage loop indices manually. This is the fix:
const numbers = [];
for (let i = 0; i <= 10; i++) {
// ↑
numbers.push(i);
console.log(numbers);
}
Most modern programming languages have better alternatives than dealing with loop indices manually in the form of higher-level abstractions such as iterators, maps, and folds. Unfortunately, ECMAScript doesn't have a Range datatype, otherwise this could simply be expressed as converting a Range to an Array.
If ECMAScript did have a Range datatype, it could for example look like one of these:
const numbers = Range(0, 10).toArray()
const numbers = Array.from(Range(0, 10))
Here is an alternative for creating the numbers Array that doesn't involve manually managing loop indices, but still requires knowing that 0 to 10 are 11 numbers:
const numbers = Array.from({length: 11}, (_, i) => i)
If you want to add the numbers at indices 3 and 6, you can simply dereference indices 3 and 6 and add the results:
console.log(numbers[3] + numbers[6])
In the comments, you asked how you would add up all numbers in the Array. Combining the elements of a collection using a binary operator is called a fold or reduce, and ECMAScript supports it out-of-the-box:
console.log(numbers.reduce((acc, el) => acc + el));
Note how there is no explicit loop, thus no explicit management of loop indices. It is simply impossible to make an off-by-one-error here.
It will be: console.log((+numbers[3]) + (+numbers[6]));
Typically, it should be console.log(numbers[3] + numbers[6]); but there's sometimes a issue that results in 36 instead of 9. The extra + signs tell javascript that it is a number.
NOTE: Remember that the first number is numbers[0]. The array starts with 0!
I wrote JavaScript code to build a max heapify which maintains the max-heap property, but I have many questions regarding the implementation:
array I test on: [1, 2, 3, 4, 7, 8, 9, 10, 14, 16]
When I test on the array when it is sorted I got:
[ 16, 14, 9, 10, 7, 8, 3, 1, 4, 2 ]
While unsorted I got:
[ 16, 14, 8, 9, 10, 2, 3, 4, 7, 1 ]
Why or why not is the max-heapify affected by the array being sorted?
I find that when the array is sorted the solution is:
[ 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 ]
Why did I get a different solution when the array is sorted, even if I find my implementation is right according to the pseudocode in CLRS?
Could you specify another procedure that doesn't use recursion while achieving the same functionality?
function BuildMaxHeap(array){
for(var i = Math.floor(array.length / 2); i >= 0; i--){
MAX_HEAPIFY(array, i);
}
return array;
}
function MAX_HEAPIFY(array, i) {
var left = 2 * i + 1;
var right = 2 * i + 2;
var largest = i;
if(left <= array.length && array[left] > array[largest]){
largest = left;
}
if(right <= array.length && array[right] > array[largest]){
largest = right;
}
if(largest != i){
var temp = array[i];
array[i] = array[largest];
array[largest] = temp;
MAX_HEAPIFY(array, largest);
}
}
As you've noticed, min/max heaps made from a set of numbers can have multiple configurations of their leaves depending on the order in which they are inserted.
You might think this 'global ordering' of leaves might arise from some emergent behavior of the underlying heap property, but a given array doesn't have a one-to-one correspondence with a particular configuration.
This occurs because of how a child is inserted and bubbled-up (swapped with parents), which will stop as soon as it is smaller than it's parent - of which there can be multiple valid candidates for a position in the heap.
This was confusing to me when I first implemented a heap as well.
Interesting question;
just to be sure,
function buildMaxHeap(array){
return array.sort((a,b)=>b-a);
}
Will also return a valid array.
Since the goal is only to provide a tree where
root has maximum value key
key stored at a non-root is at most the value of its parent
any path from root to leaf is in non-increasing order
left and right sub-trees are unrelated
( http://www.cs.toronto.edu/~krueger/cscB63h/w07/lectures/tut02.txt )
The algorithm swaps parents and children until those 4 conditions are met, so yes, if you start with a different array, then also the output can be different.
From a CodeReview perspective:
MAX_HEAPIFY -> JavaScript follows lowerCamelCase, so maxHeapify
Your indentation is off, try using something like http://jsbeautifier.org/
why call one function MAX_HEAPIFY and the other BuildMaxHeap, those names resemble each other and do not tell the reader what they do.
Other than that, there is not much to say.
Most of the tutorials that I've read on arrays in JavaScript (including w3schools and devguru) suggest that you can initialize an array with a certain length by passing an integer to the Array constructor using the var test = new Array(4); syntax.
After using this syntax liberally in my js files, I ran one of the files through jsLint, and it freaked out:
Error: Problem at line 1 character 22: Expected ')' and instead saw '4'.
var test = new Array(4);
Problem at line 1 character 23: Expected ';' and instead saw ')'.
var test = new Array(4);
Problem at line 1 character 23: Expected an identifier and instead saw ')'.
After reading through jsLint's explanation of its behavior, it looks like jsLint doesn't really like the new Array() syntax, and instead prefers [] when declaring arrays.
So I have a couple questions:
First, why? Am I running any risk by using the new Array() syntax instead? Are there browser incompatibilities that I should be aware of?
And second, if I switch to the square bracket syntax, is there any way to declare an array and set its length all on one line, or do I have to do something like this:
var test = [];
test.length = 4;
Array(5) gives you an array with length 5 but no values, hence you can't iterate over it.
Array.apply(null, Array(5)).map(function () {}) gives you an array with length 5 and undefined as values, now it can be iterated over.
Array.apply(null, Array(5)).map(function (x, i) { return i; }) gives you an array with length 5 and values 0,1,2,3,4.
Array(5).forEach(alert) does nothing, Array.apply(null, Array(5)).forEach(alert) gives you 5 alerts
ES6 gives us Array.from so now you can also use Array.from(Array(5)).forEach(alert)
If you want to initialize with a certain value, these are good to knows...
Array.from('abcde'), Array.from('x'.repeat(5))
or Array.from({length: 5}, (v, i) => i) // gives [0, 1, 2, 3, 4]
With ES2015 .fill() you can now simply do:
// `n` is the size you want to initialize your array
// `0` is what the array will be filled with (can be any other value)
Array(n).fill(0)
Which is a lot more concise than Array.apply(0, new Array(n)).map(i => value)
It is possible to drop the 0 in .fill() and run without arguments, which will fill the array with undefined. (However, this will fail in Typescript)
Why do you want to initialize the length? Theoretically there is no need for this. It can even result in confusing behavior, because all tests that use the length to find out whether an array is empty or not will report that the array is not empty.
Some tests show that setting the initial length of large arrays can be more efficient if the array is filled afterwards, but the performance gain (if any) seem to differ from browser to browser.
jsLint does not like new Array() because the constructer is ambiguous.
new Array(4);
creates an empty array of length 4. But
new Array('4');
creates an array containing the value '4'.
Regarding your comment: In JS you don't need to initialize the length of the array. It grows dynamically. You can just store the length in some variable, e.g.
var data = [];
var length = 5; // user defined length
for(var i = 0; i < length; i++) {
data.push(createSomeObject());
}
[...Array(6)].map(x => 0);
// [0, 0, 0, 0, 0, 0]
OR
Array(6).fill(0);
// [0, 0, 0, 0, 0, 0]
Note: you can't loop empty slots i.e. Array(4).forEach(() => …)
OR
( typescript safe )
Array(6).fill(null).map((_, i) => i);
// [0, 1, 2, 3, 4, 5]
OR
Classic method using a function ( works in any browser )
function NewArray(size) {
var x = [];
for (var i = 0; i < size; ++i) {
x[i] = i;
}
return x;
}
var a = NewArray(10);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Creating nested arrays
When creating a 2D array with the fill intuitively should create new instances. But what actually going to happen is the same array will be stored as a reference.
var a = Array(3).fill([6]);
// [ [6], [6], [6] ]
a[0].push(9);
// [ [6, 9], [6, 9], [6, 9] ]
Solution
var a = [...Array(3)].map(x => []);
a[0].push(4, 2);
// [ [4, 2], [], [] ]
So a 3x2 Array will look something like this:
[...Array(3)].map(x => Array(2).fill(0));
// [ [0, 0], [0, 0], [0, 0] ]
N-dimensional array
function NArray(...dimensions) {
var index = 0;
function NArrayRec(dims) {
var first = dims[0], next = dims.slice().splice(1);
if(dims.length > 1)
return Array(dims[0]).fill(null).map((x, i) => NArrayRec(next ));
return Array(dims[0]).fill(null).map((x, i) => (index++));
}
return NArrayRec(dimensions);
}
var arr = NArray(3, 2, 4);
// [ [ [ 0, 1, 2, 3 ] , [ 4, 5, 6, 7] ],
// [ [ 8, 9, 10, 11] , [ 12, 13, 14, 15] ],
// [ [ 16, 17, 18, 19] , [ 20, 21, 22, 23] ] ]
Initialize a chessboard
var Chessboard = [...Array(8)].map((x, j) => {
return Array(8).fill(null).map((y, i) => {
return `${String.fromCharCode(65 + i)}${8 - j}`;
});
});
// [ [A8, B8, C8, D8, E8, F8, G8, H8],
// [A7, B7, C7, D7, E7, F7, G7, H7],
// [A6, B6, C6, D6, E6, F6, G6, H6],
// [A5, B5, C5, D5, E5, F5, G5, H5],
// [A4, B4, C4, D4, E4, F4, G4, H4],
// [A3, B3, C3, D3, E3, F3, G3, H3],
// [A2, B2, C2, D2, E2, F2, G2, H2],
// [A1, B1, C1, D1, E1, F1, G1, H1] ]
Math filled values
handy little method overload when working with math
function NewArray( size , method, linear )
{
method = method || ( i => i );
linear = linear || false;
var x = [];
for( var i = 0; i < size; ++i )
x[ i ] = method( linear ? i / (size-1) : i );
return x;
}
NewArray( 4 );
// [ 0, 1, 2, 3 ]
NewArray( 4, Math.sin );
// [ 0, 0.841, 0.909, 0.141 ]
NewArray( 4, Math.sin, true );
// [ 0, 0.327, 0.618, 0.841 ]
var pow2 = ( x ) => x * x;
NewArray( 4, pow2 );
// [ 0, 1, 4, 9 ]
NewArray( 4, pow2, true );
// [ 0, 0.111, 0.444, 1 ]
The shortest:
let arr = [...Array(10)];
console.log(arr);
ES6 introduces Array.from which lets you create an Array from any "array-like" or iterables objects:
Array.from({length: 10}, (x, i) => i);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In this case {length: 10} represents the minimal definition of an "array-like" object: an empty object with just a length property defined.
Array.from allows for a second argument to map over the resulting array.
Sparse arrays are here! 🥳 [2021]
In modern JS engines, sparse arrays are fully supported. You can use [] or new Array(len) in any way you like, even with random access. Dictionary mode seems to be a thing of the past.
In current Chrome (and I guess any V8 environment), Arrays can have a length of up to 2^32-1 and allocation is sparse (meaning empty chunks don't use up any memory):
However, there is a catch
On the one hand, for loops work as intended, however, Array's builtin higher order functions (such as map, filter, find, some etc.) ignore unassigned elements. They require fill (or some other method of population) first:
const a = new Array(10);
const b = new Array(10).fill(0);
a.forEach(x => console.log(x)); // does nothing
b.forEach(x => console.log(x)); // works as intended
Old Version
(I removed most of the old version.) The gist was that creating a large array using new Array(largeNumber) or random accessing an array in places that have not yet been allocated would tumble it into "dictionary mode". Meaning you are using an array with indexes, but under the hood it would use a dictionary to store the values, thus messing with performance, and also with iteration behavior. Luckily that is a thing of the past.
This will initialize the length property to 4:
var x = [,,,,];
I'm surprised there hasn't been a functional solution suggested that allows you to set the length in one line. The following is based on UnderscoreJS:
var test = _.map(_.range(4), function () { return undefined; });
console.log(test.length);
For reasons mentioned above, I'd avoid doing this unless I wanted to initialize the array to a specific value. It's interesting to note there are other libraries that implement range including Lo-dash and Lazy, which may have different performance characteristics.
Here is another solution
var arr = Array.apply( null, { length: 4 } );
arr; // [undefined, undefined, undefined, undefined] (in Chrome)
arr.length; // 4
The first argument of apply() is a this object binding, which we don't care about here, so we set it to null.
Array.apply(..) is calling the Array(..) function and spreading out the { length: 3 } object value as its arguments.
Please people don't give up your old habits just yet.
There is a large difference in speed between allocating memory once then working with the entries in that array (as of old), and allocating it many times as an array grows (which is inevitably what the system does under the hood with other suggested methods).
None of this matters of course, until you want to do something cool with larger arrays. Then it does.
Seeing as there still seems to be no option in JS at the moment to set the initial capacity of an array, I use the following...
var newArrayWithSize = function(size) {
this.standard = this.standard||[];
for (var add = size-this.standard.length; add>0; add--) {
this.standard.push(undefined);// or whatever
}
return this.standard.slice(0,size);
}
There are tradeoffs involved:
This method takes as long as the others for the first call to the function, but very little time for later calls (unless asking for a bigger array).
The standard array does permanently reserve as much space as the largest array you have asked for.
But if it fits with what you're doing there can be a payoff.
Informal timing puts
for (var n=10000;n>0;n--) {var b = newArrayWithSize(10000);b[0]=0;}
at pretty speedy (about 50ms for the 10000 given that with n=1000000 it took about 5 seconds), and
for (var n=10000;n>0;n--) {
var b = [];for (var add=10000;add>0;add--) {
b.push(undefined);
}
}
at well over a minute (about 90 sec for the 10000 on the same chrome console, or about 2000 times slower).
That won't just be the allocation, but also the 10000 pushes, for loop, etc..
(this was probably better as a comment, but got too long)
So, after reading this I was curious if pre-allocating was actually faster, because in theory it should be. However, this blog gave some tips advising against it http://www.html5rocks.com/en/tutorials/speed/v8/.
So still being unsure, I put it to the test. And as it turns out it seems to in fact be slower.
var time = Date.now();
var temp = [];
for(var i=0;i<100000;i++){
temp[i]=i;
}
console.log(Date.now()-time);
var time = Date.now();
var temp2 = new Array(100000);
for(var i=0;i<100000;i++){
temp2[i] = i;
}
console.log(Date.now()-time);
This code yields the following after a few casual runs:
$ node main.js
9
16
$ node main.js
8
14
$ node main.js
7
20
$ node main.js
9
14
$ node main.js
9
19
var arr=[];
arr[5]=0;
alert("length="+arr.length); // gives 6
The simplest form is to use
Array.from({ length: 3 });
// gives you
[undefined, undefined, undefined]
Unlike Array(3) which will give you an array you can't iterate over. Array.from({ length }) gives you an array you can iterate easily.
Array.from({ length: 3 }).map((e, idx) => `hi ${idx}`);
// ['hi 1', 'hi 2', 'hi 3']
Assuming that Array's length is constant. In Javascript, This is what we do:
const intialArray = new Array(specify the value);
The array constructor has an ambiguous syntax, and JSLint just hurts your feelings after all.
Also, your example code is broken, the second var statement will raise a SyntaxError. You're setting the property length of the array test, so there's no need for another var.
As far as your options go, array.length is the only "clean" one. Question is, why do you need to set the size in the first place? Try to refactor your code to get rid of that dependency.
In addition to the answers of others, another clever way is to use Float32Array to create an array and iterate on it.
For this purpose, create an instance from Float32Array with your desired length like this:
new Float32Array(5)
This code returns an array-like that you can convert it to an array with Array.from():
Array.from(new Float32Array(5)) // [0, 0, 0, 0, 0]
You can also use fill() to change the value of items:
Array.from(new Float32Array(5).fill(2)) // [2, 2, 2, 2, 2]
And of course you can iterate on it:
Array.from(new Float32Array(5)).map(item => /* ... */ )
In most answers it is recommended to fill the array because otherwise "you can't iterate over it", but this is not true. You can iterate an empty array, just not with forEach. While loops, for of loops and for i loops work fine.
const count = Array(5);
Does not work.
console.log('---for each loop:---');
count.forEach((empty, index) => {
console.log(`counting ${index}`);
});
These work:
console.log('---for of loop:---');
for (let [index, empty] of count.entries()) {
console.log(`counting for of loop ${index}`);
}
console.log('---for i loop:---');
for (let i = 0, il = count.length; i < il; ++i) {
console.log(`counting for i loop ${i}`);
}
console.log('---while loop:---');
let index = 0;
while (index < count.length) {
console.log(`counting while loop ${index}`);
index++;
}
Check this fiddle with the above examples.
Also angulars *ngFor works fine with an empty array:
<li *ngFor="let empty of count; let i = index" [ngClass]="
<span>Counting with *ngFor {{i}}</span>
</li>
You can set the array length by using array.length = youValue
So it would be
var myArray = [];
myArray.length = yourValue;
The reason you shouldn't use new Array is demonstrated by this code:
var Array = function () {};
var x = new Array(4);
alert(x.length); // undefined...
Some other code could mess with the Array variable. I know it's a bit far fetched that anyone would write such code, but still...
Also, as Felix King said, the interface is a little inconsistent, and could lead to some very difficult-to-track-down bugs.
If you wanted an array with length = x, filled with undefined (as new Array(x) would do), you could do this:
var x = 4;
var myArray = [];
myArray[x - 1] = undefined;
alert(myArray.length); // 4