Constant Array in JavaScript - javascript

How can I keep an array of constants in JavaScript?
And likewise, when comparing, it gives me the correct result.
Example,
const vector = [1, 2, 3, 4];
vector[2] = 7; // An element is not constant!
console.log(JSON.stringify(vector));
// [1,2,7,4] ... Was edited
// OR
const mirror = [1, 2, 7, 4];
console.log(`are equals? ${vector == mirror}`);
// false !

With Object.freeze you can prevent values from being added or changed on the object:
'use strict';
const vector = Object.freeze([1, 2, 3, 4]);
vector[2] = 7; // An element is not constant!
'use strict';
const vector = Object.freeze([1, 2, 3, 4]);
vector.push(5);
That said, this sort of code in professional JS is unusual and a bit overly defensive IMO. A common naming convention for absolute constants is to use ALL_CAPS, eg:
const VECTOR =
Another option for larger projects (that I prefer) is to use TypeScript to enforce these sorts of rules at compile-time without introducing extra runtime code. There, you can do:
const VECTOR: ReadonlyArray<Number> = [1, 2, 3, 4];
or
const VECTOR = [1, 2, 3, 4] as const;

I have not investigated thoroughly, but it is inferred that JS will have immutable native types, here is a presentation:
https://2ality.com/2020/05/records-tuples-first-look.html
const vector = #[1, 2, 3, 4]; // immutable

The const keyword can be confusing, since it allows for mutability. What you would need is immutability. You can do this with a library like Immutable or Mori, or with Object.freeze:
const array = [1,2,3]
Object.freeze(array)
array[0] = 4
array // [1,2,3]

Related

Problem with Accesing array data Javascript

I want to access data of var a so it is: 245 but instead it only accesses the last one. so if i print it out it says 5
var A = [1, 2, 3, 4, 5];
var B = A[[1], [3], [4]];
console.log(B)
When accessing an object using square bracket notation — object[expression] — the expression resolves to the string name of the property.
The expression [1], [3], [4] consists of three array literals separated by comma operators. So it becomes [4]. Then it gets converted to a string: "4". Hence your result.
JavaScript doesn't have any syntax for picking non-contiguous members of an array in a single operation. (For contiguous members you have the slice method.)
You need to get the values one by one.
var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B.join(""))
var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B)
You'll need to access A multiple times for each index.
var A = [1, 2, 3, 4, 5];
var B = A[1];
console.log(A[1], A[3], A[4])
You can access them directly like that.
If you want to access index 2 for example, you should do console.log(A[1]);
You can't access multiple indices at the same time.
A variable can have only one value.
#Quentin solution resolve the problem, I wrote this solution to recommend you to create an array of index, and iterate over it.
Note: You are getting the last index, because you are using the comma operator. The comma operator allows you to put multiple expressions. The resulting will be the value of the last comma separated expression.
const A = [1, 2, 3, 4, 5];
const indexes = [1,3,4];
const B = indexes.map(i => A[i]).join``;
console.log(B);

How would one add items to the beginning of an array with Lodash?

I've been searching for a while to add items to the beginning of an array with lodash. Unfortunately I can't seem to find anything other than lodash concat (to the end of the array). The docs don't seem to say anything about it either.
I got the following code:
const [collection, setCollection] = useState({
foo: [1, 2, 3]
});
const addToCollection = (key, items) => {
setCollection(prevCollection => ({
...prevCollection,
[key]: _.concat(prevCollection[key] || [], items)
}));
};
But this concats all the items to the end. I don't want to sort them every time because that uses unnessecary processing power, I would much rather just add them to the beginning because the API always pushes the items already sorted
How would I accomplish this:
addToCollection('foo', [4, 5, 6]);
console.log(collection['foo']) // [4, 5, 6, 1, 2, 3];
Instead of what is happening now:
addToCollection('foo', [4, 5, 6]);
console.log(collection['foo']) // [1, 2, 3, 4, 5, 6];
Try swapping the arguments:
_.concat(items, prevCollection[key] || [])
Or vanilla JS is pretty easy too:
Collection.unshift('addMe', var, 'otherString' )
https://www.w3schools.com/jsref/jsref_unshift.asp#:~:text=The%20unshift()%20method%20adds,use%20the%20push()%20method.
I know you asked for lodash but I figured this is a good thing to be aware of too :)
EDIT:
To clarify, this works the same whether you're pushing defined vars, string, arrays, objects or whatever:
let yourArray = [1,2,3];
let pushArray = [1,2,3,4];
let anotherArray = [7,8,9];
yourArray.unshift(pushArray, anotherArray);
will push "pushArray" and "anotherArray" to the begining of "yourArray" so it's values will look like this:
[[1,2,3,4], [7,8,9], 1,2,3]
Happy Coding!

Error when creating a model using Core API

I tried to follow the tutorial on TensorFlow official site to create a machine learning model based on Core API. But I got the following error:
Error: Argument 'b' passed to 'matMul' must be a Tensor or TensorLike, but got 'null'
I am working on windows 10 and with tfjs#1.5.2
const tf = require('#tensorflow/tfjs');
const tfcore = require('#tensorflow/tfjs-core')
const w1 = tf.variable(tf.randomNormal([784, 32]));
const b1 = tf.variable(tf.randomNormal([32]));
const w2 = tf.variable(tf.randomNormal([32, 10]));
const b2 = tf.variable(tf.randomNormal([10]));
function model(x) {
console.log(w1);
return x.matMul(w1).add(b1).relu().matMul(w2).add(b2).softmax();
}
model(tfcore);
Could you please help me with this error?
as #edkeveked stated you need to supply two tensors for tf.matMul:
approach 1
const a = tf.tensor2d([1, 2], [1, 2]);
const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
a.matMul(b);
or approach 2
const a = tf.tensor2d([1, 2], [1, 2]);
const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
tf.matMul(a, b);
in your example, by passing in tfcore to model() you are using approach 2 and therefore need to pass a second tensor to matMul. however, if you pass a tensor to model() it should work like approach 1.
The error says it all, you are multiplying a tensor by null (the second parameter defaults to null).
tf.matMul(tensor)
You need to supply a second tensor for the matrix multiplication

JS - For Loops Pushing Array

I have an initial array,
I've been trying to change values (orders) by using pop, splice methods inside a for loop and finally I push this array to the container array.
However every time initial array is values are pushed. When I wrote console.log(initial) before push method, I can see initial array has been changed but it is not pushed to the container.
I also tried to slow down the process by using settimeout for push method but this didnt work. It is not slowing down. I guess this code is invoked immediately
I would like to learn what is going on here ? Why I have this kind of problem and what is the solution to get rid of that.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial);
}
return schedulePattern;
}
**Console.log**
(4) [1, 2, 3, 4]
(4) [1, 4, 2, 3]
(4) [1, 3, 4, 2]
(3) [Array(4), Array(4), Array(4)]
0 : (4) [1, 3, 4, 2]
1 : (4) [1, 3, 4, 2]
2 : (4) [1, 3, 4, 2]
length : 3
When you push initial into schedulePattern, it's going to be a bunch of references to the same Array object. You can push a copy of the array instead if you want to preserve its current contents:
schedulePattern.push(initial.slice(0));
Good answer on reference types versus value types here: https://stackoverflow.com/a/13266769/119549
When you push the array to schedulepattern, you are passing a reference to it.
you have to "clone" the array.
use the slice function.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial.slice());
}
return schedulePattern;
}
​
You have to know that arrays are mutable objects. What does it mean? It means what is happening to you, you are copying the reference of the object and modifying it.
const array = [1,2,3]
const copy = array;
copy.push(4);
console.log(array); // [1, 2, 3, 4]
console.log(copy); // [1, 2, 3, 4]
There are a lot of methods in Javascript which provide you the way you are looking for. In other words, create a new array copy to work properly without modify the root.
const array = [1,2,3]
const copy = Array.from(array);
copy.push(4);
console.log(array); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]
I encourage you to take a look at Array methods to increase your knowledge to take the best decision about using the different options you have.

Spread syntax doesn't work to destructive an array

I am new to Javascript and is confused why the following won't work?
var array = [1, 2, 3, 4]
var spread = ...array;
I was expecting it would become 1, 2, 3, 4. Instead, it gave an error message Unexpected token .... Can anyone explain this to me?
Thank you so much!
This is the correct way, however you're not gaining anything doing that.
var array = [1, 2, 3, 4]
var spread = [...array];
console.log(spread);
If you really want to destructure that array, you need destructuring assignment:
var array = [1, 2, 3, 4]
var [one, two, three, four] = array;
console.log(one, two, three, four);
The correct way of doing what you want is:
var array = [1, 2, 3, 4]
var spread = [...array];
The syntax for using spread is:
For function calls:
myFunction(...iterableObj);
For array literals or strings:
[...iterableObj, '4', 'five', 6];
For object literals (new in ECMAScript 2018):
let objClone = { ...obj };
So, based on the syntax, for an array by using spread you are missing the square brackets []:
var array = [1, 2, 3, 4]
var spread = [...array];
console.log(spread);

Categories

Resources