I have this question whereby I need to set up an array without any loops.
I have no idea as to where to start. I was thinking of creating the array with the desired length first and then put the elements in it. However, I don't think that'll work because it'll mean that I have to hardcode the array with the desired length?
Here's an example of creating an array that contains 3 empty arrays with .fill() and .map()
let arr = new Array(3).fill().map(()=>new Array())
.fill() is needed so that you can have values to map, .map() creates new arrays. Note that calling something like .fill(new Array()) won't work well, because it will populate it with references to the same array.
Related
Ok so in doing a simple game of life simulation I came across this really wierd problem I have a 2D array and Im trying to change one value at cords x,y simple right?
let arr = new Array(10).fill(new Array(10).fill(1))
arr[1][1] = 0
console.log(arr[3])
I've done this in the past in multiple projects but now for some strange reason now it changes all arr[x][1] instead of just arr[1][1]
new Array creates an object (almost everything in JS is object) that is used later to fill another array with THE SAME array (object, in fact) 10 times. So, what you are doing by arr[1][1] = 0; is changing object's property that gets reflected everywhere.
To prove that it is the same object everywhere in the array, try to check like arr[4] === arr[7] it will give you true.
new Array(10).fill(1) generate a reference which is being used in each slot of array. So, modifying an index of any array also update others array, as they have the same reference.
let arr = new Array(10).fill(new Array(10).fill(1))
You need to create a new reference of array for each index. You can use array#from to generate it.
const arr = Array.from({length: 10}, _ => new Array(10).fill(1));
arr[1][1] = 0
console.log(arr)
Array#fill by definition fills up the array with the same object.
You should do this:
new Array(10).fill(0).map(() => new Array(10).fill(1)));
I have an array like this(data retrieved from mySql and json_encode() in PHP, coming back as a json object(totally 19 elements in this array, and all the objects in different order in the element)):
const array=[
[{"name":"jason"},{"age":16},{"location":"London"}],
[{"age":24},{"location":"Tokyo"},{"name":"amy"}]
]
How to convert it to an array like this, removing curly brackets?
const array=[
{"name":"jason","age":16,"location":"London"},
{"name":"amy","age":24,"location":"Tokyo"}
]
I have tried to convert to string, then
String.replace(/[{}]/g, '');
But what's next? I got stuck at converting back to array again.
And the other question is:For an array like this, when to access the keys and values, is it neccesary to re-structure the keys and values to make them the same order in each element, otherwise it doesn't look nice and is not easy to access?
[
[{"name":"jason"},{"age":16},{"location":"London"}],
[{"age":24},{"location":"Tokyo"},{"name":"amy"}]
]
Any tips on how to think about flattening this will be much appreciated!
The .replace() method is used for strings, not objects/arrays. Instead, you can merge the objects within each inner array together by using .map() to trasform each array, and Object.assign() to merge the given array of objects.
See example below:
const array = [
[{"name":"jason"},{"age":16},{"location":"London"}],
[{"age":24},{"location":"Tokyo"},{"name":"amy"}]
];
const res = array.map(inner => Object.assign({}, ...inner));
console.log(res);
The order of your (string) keys in the resulting objects will appear in the order that they're inserted, so as your object order is different for each inner array, your resulting object's key-ordering will also be different once they're merged. However, this shouldn't matter too much as relying on object key ordering is often not the best idea, and can be done more reliably using other methods.
I created an object which contains an array.
I noticed that when I dont enter any values into the array, it still has one - its size,
So how can I check if the array is actually empty?
Here's how I'm creating the array:
array = { text:[10] }
The size of the array is not an array entry (aka array "element"). It is a property, length, but it's not an entry. An empty array is exactly that: empty.
The code you posted in a comment:
array = { text:[10] }
does not create an empty array. It creates an array of length 1 with the entry 10 in it.
If you want to create an empty array with a specific length, you can't do that in a single statement with an array literal ([]). You have two ways you can do it:
Using an array literal and assigning to length:
var a = [];
a.length = 10;
or using new Array:
var a = new Array(10);
But there's virtually never any reason, in JavaScript, to predefine the length of the array, because standard JavaScript arrays aren't really arrays at all. It does make sense with the new typed arrays (Uint32Array and such), and to do it you have to use the array constructor (new Uint32Array(10)).
This question already has answers here:
Copy array by value
(39 answers)
Closed 8 years ago.
sorry very basic question I'm new.
If I have an array and pass it to a new variable (newArray = oldArray) then remove an element from newArray, it seems to also effect oldArray.
my guess is that it's simply creating a new reference to the same variable, so that data that was stored in oldArray now has two identifiers?
If so how do I actually pass the elements from oldArray into newArray so that newArray is independent from oldArray?
Thanks in advance
my guess is that it's simply creating a new reference to the same variable, so that data that was stored in oldArray now has two identifiers?
Right, both your new variable and your old one are pointing to the same array. Operations on the array through one reference (variable) are naturally visible through the other one, since there is just one array.
To avoid this, you'd have to make a copy of the array. There are several ways to do that, one of which is to use slice:
var newArray = oldArray.slice(0);
slice returns a shallow copy of an array starting at the given index. If you give it the index 0, it copies the entire array.
The quickest way is to use an array function to return a new array instance. Typically, I use:
var newArray = oldArray.slice(0);
In that case you have to clone the array using the slice method:
newArray = oldArray.slice(0);
As you've learned, when you copy an array variable, you copy a reference to the original.
Here's one idom to make a real copy - request a slice from the first element
var newArray = oldArray.slice(0);
I was trying to define an array (including other arrays as values) in a single javascript statement, that I can loop through to validate a form on submission.
The function I wrote to (try to) create inline arrays follows:
function arr(){
var inc;
var tempa = new Array(Math.round(arguments.length/2));
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
This is called three times here to assign an array:
window.validArr = arr(
'f-county',arr('maxlen',10, 'minlen',1),
'f-postcode',arr('maxlen',8, 'minlen',6)
);
However in the javascript debugger the variable is empty, and the arr() function is not returning anything. Does anyone know why my expectations on what this code should do are incorrect?
(I have worked out how to create the array without this function, but I'm curious why this code doesn't work (I thought I understood javascript better than this).)
Well from what your code does, you're not really making arrays. In JavaScript, the thing that makes arrays special is the management of the numerically indexed properties. Otherwise they're just objects, so they can have other properties too, but if you're not using arrays as arrays you might as well just use objects:
function arr(){
var inc;
var tempa = {};
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
What you're seeing from the debugger is the result of it attempting to show you your array as a real array should be shown: that is, its numerically indexed properties. If you call your "arr()" function as is and then look at (from your example) the "f-county" property of the result, you'll see something there.
Also, if you do find yourself wanting a real array, there's absolutely no point in initializing them to a particular size. Just create a new array with []:
var tempa = [];
Your code works. Just inspect your variable, and you will see that the array has the custom keys on it. If not expanded, your debugger shows you just the (numerical) indixed values in short syntax - none for you.
But, you may need to understand the difference between Arrays and Objects. An Object is just key-value-pairs (you could call it a "map"), and its prototype. An Array is a special type of object. It has special prototype methods, a length functionality and a different approach: to store index-value-pairs (even though indexes are still keys). So, you shouldn't use an Array as an associative array.
Therefore, their literal syntax differs:
var array = ["indexed with key 0", "indexed with key 1", ...];
var object = {"custom":"keyed as 'custom'", "another":"string", ...};
// but you still can add keys to array objects:
array.custom = "keyed as 'custom'";