Push a dimensional array - javascript

Why the answer is undefined in the Second example?
// First
var arr = [
[1, 4, 6],
['alex']
];
var newArr = arr[1];
newArr.push('Peter');
console.log(arr);
// Second
var arr = [
[1, 4, 6],
['alex']
];
arr.push([1]['Peter']);
console.log(arr);

The code [1]['Peter'] is trying to access a key named Peter from the array literal [1]. And it is undefined
Your code is equivalent to this:
var arr = [
[1, 4, 6],
['alex']
];
var tempArray = [1];
var tempValue = tempArray['Peter'] // undefined
arr.push(tempValue);
console.log(arr);
You should change it to: arr[1].push('Peter')

That syntax [1]['Peter'] doesn't do what you might imagine. You're passing an input parameter. It doesn't reference the array pushing it into, it's completely independent. So you're effectively telling JavaScript to first create a new array ([1]), and then try to access an index called "Peter" from within it (["Peter"]), and then push that into the next free index in arr. Clearly that "Peter" index doesn't exist within the new array, which is why it outputs undefined.
Instead you'd have to write it like this, so it pushes to the existing array, which is itself at index 1 of arr:
// First
var arr = [
[1, 4, 6],
['alex']
];
var newArr = arr[1];
newArr.push('Peter');
console.log(arr);
// Second
var arr = [
[1, 4, 6],
['alex']
];
arr[1].push('Peter');
console.log(arr);

The problem is
arr.push([1]['Peter']);
But an array which contains a single element, 1, does not have the property Peter. Arrays generally do not have non-numeric properties (other than those on Array.prototype and Object.prototype)

All you need to do is
var arr = [
[1, 4, 6],
['alex']
];
arr[1].push('Peter');
console.log(arr);

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]

Call Array key of Map object

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));

How to iterate over array in reverse order with Lodash?

I want to iterate over an array in reverse order using Lodash. Is that possible?
My code looks like below.
var array = [1, 2, 3, 4, 5];
_.each(array, function(i) {
_.remove(array, i);
});
When I do _.pullAt(array, 0) new array is [2, 3, 4, 5]. All array elements shifted to left by 1 position, and current index is pointing to element 3. After next iteration, 3 will get deleted and then 5. After 3rd iteration array contains [2, 4] which I couldn't delete.
If I iterate over the array in reverse order, then this problem won't arise. In Lodash, can I iterate over an array in reverse order?
You can use _.reverse available in version 4:
var array = [1, 2, 3, 4, 5];
array = _.reverse(array)
console.log(array)
//5, 4, 3, 2, 1
See How do I empty an array in JavaScript? if you only want that and choose your weapon.
Otherwise, strictly answering the question, to iterate the indices from the length of the array to zero, you could use the "down-to" --> operator1. But that's not really necessary, even underscore isn't necessary in this case as the .pop function is enough.
var arr = [1, 2, 3, 4, 5],
index = arr.length;
while (index --> 0) {
console.log(index);
arr.pop();
}
console.log(arr);
If you're using Lodash like the functions referenced in the question seem to indicate, you could use _.eachRight.
var arr = [1, 2, 3, 4, 5];
_.eachRight(arr, function(value) {
console.log(value);
arr.pop();
});
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
1 The down-to operator doesn't exist and is only a -- decrement followed by a > comparison.

Javascript/d3 Function for creating new array from an array of arrays

Right now I have an array of the form [[1, 2], [3, 4], ...] and need to use an array of the keys [1, 3, ...] and was wondering if there was a javascript or d3 library function that took in the array of arrays and a function, then returned a new array according to the function. Something like this:
var data = [[1, 2], [3, 4]]
var keyArray = d3.transformArray(data, function(d) { return d[0]});
// keyArray = [1, 3]
So I can avoid looping over the data array again
var keyArray = [];
for (i = 0; i < data.length; i += 1) {
keyArray.push(data[i][0]);
}
// keyArray[1, 3]
This seems like a common enough thing to do using d3, but I wasn't sure if there's a specific name for this process of using a specific object and a function to create a new object of the same type.
you can use Array.prototype.map
x = [1,2,3].map(function(item){return item+1;});
this will result int [2,3,4]
read about this here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

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