Can't tell if my browser console is bugged, or what is going on, as I've never had issues using the reverse function.
When I throw the following into my chrome console,
var a = ['one', 'two', 'three'];
var reversed = a.reverse();
console.log(a); // ['one', 'two', 'three']
console.log(reversed); // ['three', 'two', 'one']
I get
Array#reverse works in place and doesn't create a new array. The line
var reversed = a.reverse();
reverses a and also sets reversed to reference the same array.
In this example you can see that adding an item to reversed also affects a because they reference the same array:
var a = ['one', 'two', 'three'];
var reversed = a.reverse();
reversed.push(1000); // add something to reversed
console.log(a); // ['three', 'two', 'one', 1000]
console.log(reversed); // ['three', 'two', 'one', 1000]
To create a new array use Array#slice on the original, and then reverse the array:
var a = ['one', 'two', 'three'];
var reversed = a.slice().reverse();
console.log(a); // ['one', 'two', 'three']
console.log(reversed); // ['three', 'two', 'one']
The reverse function mutates the current array. After you declare reversed to be a.reverse(), the array a will be mutated as well. Thus, you will print out ['three', 'two', 'one'] for console.log(a) and console.log(reversed)
What you want to do is to make a clone of a:
var a = ['one', 'two', 'three'];
var reversed = a.slice().reverse();
console.log(a); // ['one', 'two', 'three']
console.log(reversed); // ['three', 'two', 'one']
Related
I'm looking for a simple method to iterate over an array and generate a result like below... Better if someone can show me how to do this in the ES2015 way.
var numbers = ['one', 'two', 'three'];
/* Expected result */
/*
0: ['one', 'two', 'three'],
1: ['one', 'two'],
2: ['one']
*/
https://jsfiddle.net/minuwan/1eL83sbz
You could map the sliced array.
var numbers = ['one', 'two', 'three'],
result = numbers.map(function (_, i, a) {
return a.slice(0, a.length - i);
});
console.log(result);
You can use slice to get the output you want instead of using pop since it will modify your numbers array
var numbers = ['one', 'two', 'three'];
var array = [];
var arrayLength = numbers.length;
for (var i = 0; i < arrayLength; i++) {
array[i] = numbers.slice(0, arrayLength - i);
}
console.log(array);
or you would simply use map with slice
var numbers = ['one', 'two', 'three']
var array = numbers.map(function (_, i) {
return numbers.slice(0, numbers.length - i);
});
console.log(array);
What is a concise and the efficient way to remove elements of a Map object in a single loop upon some condition?
Iterating on the map's entries() can do it but calling entries() at each iteration doesn't look efficient
let name_value_map = new Map([['One', 1], ['Two', 2], ['Three', 3], ['Four', 4]])
for (let pair of name_value_map.entries())
if (pair[1] <= 3)
name_value_map.delete(pair[0])
Other ideas?
Use the Map.forEach() method:
const name_value_map = new Map([['One', 1], ['Two', 2], ['Three', 3], ['Four', 4]]);
name_value_map.forEach((v, k, m) => v <= 3 && m.delete(k));
console.log([...name_value_map.entries()]); // SO console doesn't display Map
Use entries and filter along with spread operator ...
name_value_map = new Map([...name_value_map.entries()].filter( s => s[1] > 3 ));
Demo
var name_value_map = new Map([
['One', 1],
['Two', 2],
['Three', 3],
['Four', 4]
]);
name_value_map = new Map([...name_value_map.entries()].filter(s => s[1] > 3));
console.log(name_value_map); //check the browser's console
You can use Array.from, then use .filter, and convert back to Map. This won't mutate the orginal Map.
The Array.from() method creates a new Array instance from an
array-like or iterable object.
let name_value_map = new Map([['One', 1], ['Two', 2], ['Three', 3], ['Four', 4]])
const filtered = new Map(
Array.from(name_value_map).filter(([,value]) => value > 3)
);
console.log([...filtered.entries()])
Why not to use an object ?
const ob = {
One: 1,
Two: 2,
Three: 3,
Four: 4
};
for (const key of Object.keys(ob)) {
if (ob[key] <= 3)
delete ob[key];
}
I seen a code snippet like the below. Can anybody please tell me what
var [input] = data; var [checkbox, payee, amount] = data2;
means?
function example(data,data2){
var [input] = data;
var [checkbox, payee, amount] = data2;
............
............
}
As Nina Scholz stated in her comment, it's a destructuring assignment.
If data2 was an array of [1, 2, 3], then var [checkbox, payee, amount] = data2; is the same as:
var checkbox = data2[0]; // 1
var payee = data2[1]; // 2
var amount = data2[2]; // 3
Rest parameter
You can using destructuring with rest parameter like in the example below, to save multiple elements into an array.
const digits = [1, 2, 3, 4, 5];
const [one, ...other] = digits;
console.log(one);
console.log(other);
Omitting values
You can ignore the values you're not interested in, like this:
const myArray = ["car", "cat", "house", "dog", "window", "mouse"];
const [, cat, ,dog, , mouse] = myArray;
console.log(cat, dog, mouse);
or like this:
const myArray = ["John", "Mary", "Steve", 0, 1, 2];
const [name1, name2, name3] = myArray;
console.log(name1, name2, name3);
It's a destructuring assignment with an array/iterable object (with implemented Symbol.iterator) with values to assign.
The value goes into the variable with the same index as the given data.
For getting only some parts at a certain index, you could use an object with indices as keys.
var array = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
[zero, one] = array,
{ 3: three, 10: ten } = array;
console.log(zero);
console.log(one);
console.log(three);
console.log(ten);
This is just the destructuring assignment
var t = [1,2];
var [a,b] = t;
console.log(a);
console.log(b);
When used on arrays, it assigns consecutive array elements to variables introduced at the left side of the assignment operator.
This is Destructuring assignment.
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.
As per your example,
var data = [1];
var [input] = data;
console.log(input); //1
I have two separate arrays which looks something like this
var x = ['one', 'two', 'three'];
var y = ['1', '2', '3'];
I am doing this to combine them
var newArray = [];
for (var i = 0; i < x.length && i < y.length; i++) {
newArray[i] = [x[i], y[i]];
}
desired output
newArray = [
['one', '1'],
['two', '2'],
['three', '3']
]
This is my fiddle: http://jsfiddle.net/sghoush1/EjRPS/4/
On ES5 you can use Array.prototype.map to simplify your loop:
var newArray = x.map(function(n, i) {
return [n, y[i]];
});
See the above link for a shim for older browsers.
If you have Underscore.js, you can use:
var newArray = _.zip(x, y);
This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 9 years ago.
Is there a common Javascript/Coffeescript-specific idiom I can use to accomplish this? Mainly out of curiosity.
I have two arrays, one consisting of the desired keys and the other one consisting of the desired values, and I want to merge this in to an object.
keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']
var r = {},
i,
keys = ['one', 'two', 'three'],
values = ['a', 'b', 'c'];
for (let i = 0; i < keys.length; i++) {
r[keys[i]] = values[i];
}
console.log(r);
.as-console-wrapper { max-height: 100% !important; top: 0; }
keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']
d = {}
for i, index in keys
d[i] = values[index]
Explanation:
In coffeescript you can iterate an array and get each item and its position on the array, or index.
So you can then use this index to assign keys and values to a new object.
As long as the two arrays are the same length, you can do this:
var hash = {};
var keys = ['one', 'two', 'three']
var values = ['a', 'b', 'c']
for (var i = 0; i < keys.length; i++)
hash[keys[i]] = values[i];
console.log(hash['one'])
console.log(hash.two);