This question already has answers here:
What is SpreadElement in ECMAScript documentation? Is it the same as Spread syntax at MDN?
(3 answers)
Closed 6 years ago.
I found the following case in javascript. I don't understand '...' operator mean here. I search it on the Google, but I did not get anything about it. Is there any other usage for this operator? Can someone help me out?
var x= [1,2,3];
var y = [4,5,6];
var z = [...x, ...y]; // z will be [1,2,3,4,5,6];
Thanks.
I have a way of thinking which makes it very easy to understand and remember how '...' works.
var arr = [1,2,3] // this is arr which is the array
on the other hand
...arr // this is whatever inside arr, which is 1,2,3
So you can also think of it as taking what is inside of an array.
Note that by its own, ...arr is not a valid syntax. You can use it in
many ways , two of them coming to my mind are :
1 - Pass what is inside an array to a function
var arr = [ 1,2,3 ]
var myFunc = function(a,b,c) {
console.log(a,b,c)
}
myFunc(..arr) // logs 1 2 3
myFunc(1,2,3) // logs 1 2 3
2 - Take what is inside of an array and use them in another array.
var arr = [ 1,2,3 ]
var foo = [ ...arr, 4,5,6 ] // now foo is [ 1,2,3,4,5,6 ]
Related
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 4 months ago.
In Javascript, I have this
var a = ["1","2","3"]
var b = ["3","4","5"]
assuming "b" reads "a" and removes the 3 because it is repeated, how can I get this?
var c = ["4","5"]
Thank You!
You can use set and spread operators.
set has property to have all unique value object.
Below we are using Set constructor passing values using spread operator and it return an object so to get an array we are again passing that object with spread operator.
let a = ["1", "2", "3"]
let b = ["3", "4", "5"]
let c = [...new Set([...a, ...b])];
console.log(c);
Check if value exists on another array using includes()
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
You can remove values by using filter()
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
To do what you want:
const a = ["1","2","3"]
const b = ["3","4","5"]
const c = b.filter((value) => !a.includes(value))
This has been answered before and is in detail: How to get the difference between two arrays in JavaScript?
This question already has answers here:
Copy array items into another array
(19 answers)
Closed 2 years ago.
I have this:
z: [[res.push(this.Map.heatmap[0])]],
so this is just one value. But how can I push all the values of the array
and this is the interface:
export interface map {
}
I have a array of 100 values in it:
10
but if I do this:
this.Map().subscribe((res) => {
zsmooth: 'best'
}
],
not all the values are loaded. So how to load all the values?
and this is how I have the object:
Map: map = {};
Thank you
Oke,
console.log(res)
gives back array with 100 values:
length: 100
but apperently this:
z: [[res]],
doesn't work. I dont see the value at all.
But if I do this:
hallo: console.log(res.push(this.Map.map[0])),
z: [[res.push(this.cMap.tmap[0])]],
it returns the number 2
concat function is maybe what you are looking for:
var array1 = [A, B, C];
var array2 = [D, E, F];
var newArray = array1.concat(array2);
The newArray will be [A,B,C,D,E,F]
In your case you would do something like:
z = z.concat(this.cameraAgretateHeadMap.heatmap)
a little bit more code from your side would have been helpful to understand it in a better what your problem is!
Hopefully this helps!
It's always tricky to think Array.concat thing. Often, I just want to use mutable Array.push because I simply add extra-data on the immutable data. So, I usually do:
array[array.length] = newData;
I've asked a question related got some answers here: How to store data of a functional chain
const L = (a) => {
const m = a => (m.list ? m.list : m.list = [])
.push(a) && m;
//use `concat` and refactor needed instead of `push`
//that is not immutable
return m(a); // Object construction!
};
console.log(L);
console.log(L(2));
console.log(L(1)(2)(3))
some outputs:
{ [Function: m] list: [ 2 ] }
{ [Function: m] list: [ 1, 2, 3 ] }
I feel that push should be replaced with using concat, but still, push makes the code elegant simply because we don't want to prepare another object here.
Basically, I want to do:
arr1 = arr1.concat(arr2);
but, is there any way to write
arr1[arr1.length] = arr2;
which ends up with a nested array, and does not work.
You could assign a new array with a default array for not given m.list.
const L = (a) => {
const m = a => (m.list = (m.list || []).concat(a), m);
return m(a);
};
console.log(L.list);
console.log(L(2).list);
console.log(L(1)(2)(3).list);
You can use multiple parameters in Array.push so:
var a = [];
a.push(3, 4) // a is now [3, 4]
Combined with the ES6 spread syntax:
var a = [1, 2];
var b = [3, 4]
a.push(...b); // a is now [1, 2, 3, 4]
arr1[arr1.length] represents a single value, the value at index arr1.length.
Imagine this array
[ 1 , 2 , 3 , 4 ] // arr of length 4
^0 ^1 ^2 ^3 // indexes
If we say arr1[arr1.length] = someThing
We ask javascript to put something right here, and only here, at index 4:
[ 1 , 2 , 3 , 4 , ] // arr of length 4
^0 ^1 ^2 ^3 ^4 // add someThing in index 4
So, if we want to add something strictly with arr1[arr1.length], then we need to keep doing that for each index. for each meaning any kind of loop. E.G:
// Not recommended to use
var arr1 = [1,2,3];
var arr2 = [3,4,5];
while (arr2.length){
arr1[arr1.length] = arr2.shift();
}
console.log(arr1); // [1,2,3,3,4,5]
console.log(arr2); // []
But, as you can see, this method, or any similar one, even if optimized, is not the right approach. You need a concatenation.
Since you mention a functional one, which returns the resulting array, you can simply replace the initial array and make use of spread operator:
var arr1 = [1,2,3];
var arr2 = [3,4,5];
console.log(arr1 = [...arr1,...arr2]); // [1,2,3,3,4,5]
This question already has answers here:
Why is [] !== [] in JavaScript? [duplicate]
(3 answers)
How to check if two arrays are equal with JavaScript? [duplicate]
(16 answers)
Closed 4 years ago.
This appears as a very basic question, but couldn't find any explanations on SO.
Consider this:
var arr = [1, 2, 3];
var str = "123";
function compare(){
return arr.join('').split('') === str.split('')
}
console.log(compare());
console.log(arr.join('').split(''))
console.log(str.split(''))
Cant understand why console logs false...?
Because although the two arrays you're comparing are equivalent, they are not the same array. == (and ===) with objects checks to see if they're the same object.
What you have, in effect, is:
console.log(["1", "2", "3"] == ["1", "2", "3"]);
You compare two objects' references, not their content. Because you have 2 different objects, their references are not equal.
=== with reference types will return true if 2 variables refer to the same object. In the below example both a and b refer to the same object (same part in the memory), so they are equal.
const a = {};
const b = a; // assign `a`'s value, which is a reference to the `b`
console.log(a === b);
They are not same array & they are separate object reference. If you want to compare these two , then stringify them
var arr = [1, 2, 3];
var str = "123";
function compare() {
return (arr.join('').split('')).toString() === str.split('').toString()
}
console.log(compare());
console.log(arr.join('').split(''))
console.log(str.split(''))
This question already has answers here:
Functional approach to basic array construction
(5 answers)
Closed 8 years ago.
I'm trying to create a function that returns an array with n elements, that are all the same function (this array will later be used to call those functions in parallel using async).
I can easily loop over an array and add the function to each element, but was wondering if I can do it in one line, using map:
//the function to point to
var double = function(x) {
return x*2;
};
//this function will create the array - just a filler for a one-liner
var createConsumersArray = function(numOfConsumers) {
var consumers = (new Array(2)).map(function(x){return double;});
return consumers;
};
var t = createConsumersArray(2);
console.log(t); //prints [,]
console.log(t[1](2)); //TypeError: Property '1' of object , is not a function
If I pre-fill the array with constants, the map works, i.e.:
var x = [1,2,3];
console.log(x.map(function(x){return double;})); //prints [ [Function], [Function], [Function] ]
console.log(x[1](2)); //prints 4
How can I accomplish filling an array with an identical function in the shortest way?
You have to change a little.
var createConsumersArray = function(numOfConsumers) {
var consumers = Array.apply(null, Array(numOfConsumers)).map(function(){return double;});
return consumers;
};
This is more functional programming. If you'd like to program in this style, I'd recommend you look at underscore.js. Here's an example of a range function:
_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
For your use case you would do:
_.map(_.range(4), function(num){ return double; });
Here's the corresponding jsfiddle example: