This question already has answers here:
Javascript - Loop through array backwards with forEach
(10 answers)
Closed 3 years ago.
I need create a function that prints an array in reverse. The array is:
var array = [1,2,3,4,5]
My attempt is:
function printReverse(){
for (i = array.length ; i >= 0;i--){
console.log(array[i]);
}
}
So i wonder if you can create the same think with foreach.
I could not find anything in the web about it
forEach will strictly 'enumerate' forward through the array, but the callback to forEach will be passed three arguments: the current item, the index of that item, and a reference to the original array. You can use the index to walk backwards from the end. For example:
var array = [1, 2, 3, 4, 5];
array.forEach((_, i, a) => console.log(a[a.length - i - 1]));
Another trick is to use reduceRight to enumerate the items in reverse. The callback here will be passed an accumulator as the first argument (which you can simply ignore) and the item as the second argument. You'll have to pass in a value to initialize the accumulator as well, but again it doesn't really matter what that value is since you'll be ignoring it in this case:
var array = [1, 2, 3, 4, 5];
array.reduceRight((_, x) => console.log(x), 0);
Related
This question already has answers here:
Js remove element from array without change the original
(4 answers)
Closed 13 days ago.
If I have an array a = [1,2,3,4] and I want to return it with the 3 removed, there are two ways I can do it:
let b = [...a] // or a.slice()
b.splice(2,1)
return b
or
return [...a.slice(0,2), ...a.slice(3,4)]
Advantage of the second is that it's one line. Disadvantage is that it's verbose. I thought of writing a helper function that contains the logic of the first approach, so that I'd be able to call it in one line elsewhere.
Is there an alternative? Something like splice but that returns that spliced array rather than mutating it and returning the spliced-out elements.
Since you know the indicies you want to remove, you can use the Array.prototype.filter method.
const a = [1,2,3,4];
const b = a.filter((_, i) => i !== 2);
console.log(b);
If you need to remove a range, you can just do something like 2 < i || i > 3.
.filter makes a copy of the array, copying the values where the callback function evaluates truthy and ignores the values where the callback function evaluates falsy.
This question already has answers here:
How to compare arrays in JavaScript?
(61 answers)
sorting an array and comparing it to the original
(6 answers)
Closed 12 months ago.
Let's say we have an array of numbers in Javascript:
const arr = [1,3,2,6,5,3];
We sort it using the native sort method:
arr.sort(); // OR arr.sort((a, b) => a - b)
Now how do the unsorted and sorted array equal to one another?
console.log(arr === arr.sort()) // logs true
I am aware the sort method does not create a new array, so they would both point to the same address on the memory.
However, their element order is different, and since arrays are list-like objects, with enumerable indices, the order of elements do matter unlike objects.
So, if all above is true, how are they strictly equal?
const arr = [1, 3, 2, 6, 5, 3];
arr.sort(); // OR arr.sort((a, b) => a - b)
console.log(arr === arr.sort()) // logs true
arr === arr.sort() compares the reference of the arrays. arr.sort is an in-place sort. It doesn't create a new array. arr and arr.sort() reference the same object.
They are strictly equal because both types (object) are same and both values (references) are same.
The comparison doesn't consider the values of the arrays.
[1,2,3] === [1,2,3] returns false, because the references are different.
This question already has answers here:
Square brackets surrounding parameter in function definition
(3 answers)
Closed 4 years ago.
var a = {a:{bb:"mm"},b:{bbb:"bb"}}
var v= Object.entries(a)
// a print array items value that is fine
v.map((a,b)=>{console.log(a)})
// print the index that is fine
v.map((a,b)=>{console.log(b)})
// why it print
//
//{bb: "mm"}
//{bbb: "bb"}
v.map(([a,b])=>{console.log(b)})
//output
https://jsbin.com/zevuqedupa/edit?html,js,console,output ..why not print index
Hi
my question why it is printing in object.Is it destructing of es2015? is it es6 part ?
The Object.entries(..) method accepts an object and returns an array of key-value pairs, that are other arrays where the first element is the key and the second element is the value.
In this case, the v variable will be:
[['a', {bb: 'mm'}], ['b', {bbb: 'bb'}]];
The map method will iterate on each of the inner array.
So, on the first iteration it will receive, as first parameter:
['a', {bb: 'mm'}]
On the second iteration ti will receive, as first parameter:
['b', {bbb: 'bb'}]
Now we go to destructuring. When you pass the square brackets in the first parameter, you say:
Hey, the first parameter will be an array, let a be the first element of the array and let b be the second element of the array.
You print b, so you print the second element of the array at each iteration, and that is the value.
If you want, you can also print the index, since [a, b] is the first parameter altogether.
v.map(([a,b], index) => {console.log(`value: ${b}, index: ${index}`)})
(a,b)=>{console.log(b)}
Expects 2 parameters named a and b and is called like f(a,b);
([a,b])=>{console.log(b)}
Expects and array and names the 0 and 1 indexes a and b and is called like f([a,b])
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 6 years ago.
I have found that these two different methods of creating an array of arrays produce different behaviors:
// Method 1
for (var arr1 = []; arr.push([]) < len;) {}
// Method 2
var arr2 = new Array(len).fill([])
The arrays created look the same in the console, however they behave differently in my code. What could be causing this?
The difference is that in the 1st method each index points to a different array, while in the Array#fill all indexes point to the same array.
Note: the 1st method will not create an array of arrays
var len = 3;
var arr1 = [];
// Method 1
for (var arr1 = []; arr1.push([]) < len;) {} // new sub array is pushed into arr1
// Method 2
var arr2 = new Array(len).fill([]) // each place in the array is filled with a reference to the same array
arr1[0].push(1); // push to the 1st element of arr1
arr2[0].push(1); // push to the 1st element of arr2
console.log('arr1: ', JSON.stringify(arr1)); // only the 1st sub array contains 1
console.log('arr2: ', JSON.stringify(arr2)); // all sub arrays contain 1
Update: While the answer below is technically accurate, and is another difference between the two methods, #Ori Drori's answer is almost certainly what the OP is looking for.
I'll take a stab at this, but more context would be helpful.
In common practice, these two statements typically behave the same, but there is a key difference - when you use the new keyword, the Javascript interpreter calls the Array constructor.
If you were to overwrite the Array constructor, this would only apply to arr2 which was defined with the new keyword. arr1 created with the array literal would still be a Javascript array.
As an example, let's say I wrote the following code:
function Array() {
}
Method 1 would still work, but Method 2 would return a TypeError indicating that fill is not a function.
Interestingly, using the Array literal (Method 1) still calls the Array constructor, so if I did a console.log("test"); within the Array construction this would still be printed to the console when using either method. BUT, when the Array literal (Method 1) is used, the object itself still remains a standard Javascript array even if the Array constructor is overwritten.
This question already has answers here:
Undefined values in Array(len) initializer
(5 answers)
Closed 6 years ago.
I want to create empty array with fixed length, and then use .map on it to return new array. However, it's not working as expected.
According to mdn docs:
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number.
new Array(3) returns [undefined × 3]. Shouldn't it be: [undefined, undefined, undefined]?
Let's consider following examples:
1) Not working.
var a = new Array(3);
a.map((x, i) => i); // [undefined × 3]
2) Working.
var a = Array.apply(null, new Array(3));
a.map((x, i) => i); // [0, 1, 2]
I tested this on latest Google Chrome Canary.
From the MDN: this returns a new JavaScript array with length set to that number
The Array created by new Array(n) does not have any elements, only a length. That's why you can't map the (not existing) elements.
map skips over undefined elements, by design.
From the documentation:
callback is invoked only for indexes of the array which have assigned values
There are many questions here on SO related to this topic, and providing ways to create arrays that map will operate on all elements of, such as
new Array(3) . fill() . map(...
to take just one example, using the new Array#fill method.
An example in a addition to CodeiSirs answer:
// foo and bar are identical. They are arrays with length 3 and no indices.
var foo = new Array(3);
var bar = [];
bar.length = 3;
console.log(foo);
console.log(bar);
// This is different. It has 3 indices with the value undefined.
var pez = [undefined, undefined, undefined];
console.log(pez);
The console displays new Array(3) kind of weird because it's not the same as [undefined, undefined, undefined]