Call Array key of Map object - javascript

Does anyone knows how to directly call a array key of a Map Object.
As shown in below code, I can map.get(arr), but not map.get([0, 1, 2, 3])
const map = new Map()
const arr = [0,1,2,3]
map.set(arr, "I am some number")
map.get(arr) // "I am some number"
map.get([0,1,2,3]) // undefined

You can't. Map compares objects by object identity. [0, 1, 2, 3] !== [0, 1, 2, 3] as they are different objects, even if they hold the same data.
The nearest thing you can do is to try to convert the array to something you can compare meaningfully:
const map = new Map()
const arr = [0,1,2,3]
map.set(JSON.stringify([0, 1, 2, 3]), "I am some number")
console.log(map.get(JSON.stringify([0, 1, 2, 3])))

That's correct, you have to use the same array (as in map.get(arr)), not just an equivalent array. Key comparison is like === (except that NaN matches itself). So just like this shows false:
console.log([0, 1, 2, 3] === [0, 1, 2, 3]); // false
...using map.get([0, 1, 2, 3]) is guaranteed not to find anything, because there isn't any entry in the map keyed by that array.

Separate arrays aren't === to each other - your arr does not refer to the same array container as the [0,1,2,3] that you pass to map.get. To do something like this, you'd have to iterate over the map's keys and find the one whose values all match:
const map = new Map()
const arr = [0,1,2,3];
map.set(arr, "I am some number")
// Get a reference to the same `arr` whose key you set previously:
const arrKey = [...map.keys()].find(
key => Array.isArray(key) && JSON.stringify(key) === JSON.stringify([0, 1, 2, 3])
);
console.log(map.get(arrKey));
(but this is a pretty ugly thing to have to do - if you find yourself having to do this, usually it'd be better to use a different data structure)

You need the same object reference for getting the value from a Map.
If you like to use a starting part of the array as key, you need to get all keys from the map and check against with the new array.
var map = new Map,
key0 = [0, 1, 2, 3],
key1 = [0, 1, 2, 3];
map.set(key0, "I am some number");
console.log(map.get(key0)); // "I am some number"
for (let key of map.keys())
if (key.join('|') === key1.join('|'))
console.log(map.get(key));

Related

Can I point to an array using a value with the same name as the array?

I've got 50 different lists, called list1, list2, and so forth. I also have a function which rolls a random number between 1 and 50 and then stores the value in a variable called randomNumber, and what I want to do is to access the list with a matching number.
My attempt at access the list looked like this:
document.getElementById("demo").innerHTML = list + randomNumber;
One solution would be to put all 50 lists into one list, and then use the randomNumber to access the right list through index. I am however still curious if this can be done in a way similar to what I was decribing above the code though.
Inserting the arrays into another array and accessing them by their indexes (or assigning them to property values on an object and accessing them by their associated property names) is the right approach.
The only way to reference scoped variables by strings representing their names is by using eval().
However, I will echo the linked MDN article: Don't do this.
⚠️ Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). See Never use eval()!, below.
Here's an example of using eval to reference each of the arrays below:
const list1 = [1, 2, 3];
const list2 = [4, 5, 6];
console.log(eval('list' + '1')); // [1, 2, 3]
console.log(eval('list' + '2')); // [4, 5, 6]
And here's an example of the recommended approach:
const list1 = [1, 2, 3];
const list2 = [4, 5, 6];
// As an object:
const listNames = {
list1,
list2,
};
// As an array:
const lists = [
list1,
list2,
];
console.log(listNames['list' + '1']); // [1, 2, 3]
console.log(lists[0]); // [1, 2, 3]
console.log(listNames['list' + '2']); // [4, 5, 6]
console.log(lists[1]); // [4, 5, 6]

Javascript const is changeable?

I'm trying to delete max value from arMin and min value from arMax, but arr (is a const!) changes too! I don't know why. I am using Google Chrome version 65.0.3325.181.
'arr' is only one time declared and it shouldn't do nothing with that. I can't understand that. Tried with delete, but it's turning numbers into 'empty', but works the same and changes const too!
It's my first post, so if I do something wrong please forgive me.
const arr = [1, 2, 3, 4, 5];
let arMin = arr;
let arMax = arr;
let min = arMin.indexOf(Math.min.apply(null, arMin));
let max = arMax.indexOf(Math.max.apply(null, arMax));
arMin.splice(max, 1);
arMax.splice(min, 1);
console.log(arMin); // [2,3,4]
console.log(arMax); // [2,3,4]
console.log(arr); // [2,3,4]
The value of arr is a reference to an array.
You cannot change that. It will always be a reference to that array.
Arrays are mutable though, so you can change values in the array. const won't prevent that.
If you want arMin and arMax to be different arrays, then you need to make a copy of the array and not just copy the value of arr (which is a reference to that array).
const makes the reference constant, not the value.
You can't make arr point to something else, but you can change its values.
Note: other languages, Dart comes to mind, have the ability of specifying constant values. That's not the case of JavaScript.
When you make an array const then you can not change the reference
const arr = [1,2,3]
arr = [4,5,6] \\ Throws errors; You can not change const reference
arr[1] = 6; \\ Works fine. You are not changing the const reference. You are just mutating the array.
const x = 5; \\ Here constant is the value
x = x + 1; \\ Error. You can not change the constant value;
As a constant, you can't reassign its value, in this case, it contains the reference to the array.
But the array itself is not immutable.
An example would be:
const arr = [0,1,2,3,4,5];
arr = 'foo' // You cannot do that
arr.push(6) // That works fine. result: [0,1,2,3,4,5,6]
To complete previous answer, to make an exact copy of array instead of copying reference, you should do something like this :
const arr = [1, 2, 3, 4, 5];
let arMin = [...arr]; // We use spread operator to create new array from original one.
let arMax = [...arr];
let min = arMin.indexOf(Math.min.apply(null, arMin));
let max = arMax.indexOf(Math.max.apply(null, arMax));
arMin.splice(max, 1);
arMax.splice(min, 1);
console.log(arMin); // [1, 2, 3, 4]
console.log(arMax); // [2, 3, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
--- EDIT 1 ---
i use TypeScript synthax to illustrate type
const arr = [1, 2, 3, 4, 5];
arr.push(6); // Is allow.
const object: {id: number, title: string} = {id: 1, title: 'Yanis'};
object.id = 2; // Is allow.
const myString: string = 'yanis';
myString = 'Jackob'; // Not allow.

how to implement hashmap

i use hashmap in order to store the key value pair of the map.Please suggest me if their is an alternative way to do the same using NOdejs.
var HashMap=require('hashmap');
var map=new HashMap();
map.set("amit",[1,2]);
map.set("amit",[3,4]);
console.log(map.get("amit"));
On console it print [3,4], i want [1,2,3,4].
How am i going to approach this.
if value in the value variable repeated then i also want to increase the count of the value corresponding to the same key.
You are overwriting the amit keys value every time you call set on that key. Unless there is some specific API support in hashmap, your best bet is to concatenate the previous value on every set call.
Consider:
var HashMap = require("hashmap")
var map = new HashMap()
map.set('amit', [1,2])
// Concat previous value with [3, 4]
map.set('amit', map.get('amit').concat([3,4]))
console.log(map.get('amit'))
// [1, 2, 3, 4]
You could also make an abstraction for this. The following is a simple example, you would most likely want to extend it further in a real use-case.
// concatSet('foo', [1, 2])
// concatSet('foo', [3, 4])
// console.log(map.get('foo')) => [1, 2, 3, 4]
function concatSet(key, value) {
// empty array if not exists
var prevValue = map.get(key) || []
return map.set(key, prevValue.concat(value))
}
You have to loop the map.
map.set(1, "test 1");
map.set(2, "test 2");
map.set(3, "test 3");
map.forEach(function(value, key) {
console.log(key + " : " + value);
});
https://www.npmjs.com/package/hashmap

Javascript:: Find differences between array that contains duplicated values to a unique array of that array

I found many posts on stack overflow about that similar subject but none of them solve this issue here.
<script>
//Array GanginaA contains duplicated values.
//Array GanginaB contains only unique values that have been fetched from GanginaA
GanginaA=[0,1,2,3,4,5,5,6,7,8,9,9];
GanginaB=[0,1,2,3,4,5,6,7,8,9];
var hezi=<!--The Magic Goes Here-->
console.log(hezi);
/*
* Expected Output:
* 5,9
*/
</script>
GanginaA will always be longer or identical to GanginaB so there is no reason to calculate by the value of the longer array length.
GanginaB will always contains unique values that taken from GanginaA so it will always be the shorter array length or identical to GanginaA array.
Now it makes it a lot easier to find doubles.
You can use filter to get the elements like below
GanginaA = [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9];
GanginaB = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var hezi = GanginaB.filter(function (item, index) {
return GanginaA.indexOf(item) !== GanginaA.lastIndexOf(item)
});
console.log(hezi.join(" , ")); // 5, 9
the easier I can think of :
var hezi=[];
for (var i=0;i<GanginaA.length;i++){
hezi[GanginaA[i]] = GanginaA[i];
hezi[GanginaB[i]] = GanginaB[i];
}
hezi = hezi.filter (function(el){return el!=undefined;});
does everything in O(n) actions and not O(n^2)
Javascript's objects have hashmap like behaviour, so you can use them kind of like a set. If you iterate over all the values and set them to be keys within an object, you can use the Object.keys method to get an array of unique values out.
function uniqueValues() {
var unique = {};
[].forEach.call(arguments, function(array) {
array.forEach(function(value) {
unique[value] = true;
});
});
return Object.keys(unique);
};
This function will return the unique elements in any number of arrays, passed as arguments.
uniqueValues([1, 2, 3], [ 1, 1, 1], [2, 2, 2], [3, 3, 3]); // [ 1, 2 3 ]
One drawback to this method is that Javascript coerces all keys to strings, you can turn them back into numbers by changing the return statement to:
return Object.keys(unique).map(Number);

Adding new content to an javascript array

I have a numeric javascript array, that contains several objects with geodata in it.
What I need to do is, to add a dynamic count of new objects after a specific object in this array.
I know, that there is the splice function, but i do not know, how to make the count of new objects variable.
myArray.splice( pos, 0, ... );
What am I getting wrong?
Hope I understood what you meant.
var
oldA = [1, 2, 3],
newA = [4, 5];
oldA.splice.apply(oldA, (function (index, howMany, elements) {
// this is actually building the arguments array (2nd parameter)
// for the oldA.splice call
elements = elements.slice();
elements.splice(0, 0, index, howMany);
return elements;
}(/*index to insert at*/ 2, /*howMany to remove*/ 0, /*elements to insert*/ newA)));
console.log(oldA, newA); // [1, 2, 4, 5, 3] [4, 5]

Categories