I have a table of cells that need to be manipulated in a few specific spots accords to data I get
let arr = Array(3).fill(Array(3).fill(0));
[{x: 0, y: 0, value: 1}, {x: 1, y: 0, value: 2},{x: 2, y: 0, value: 3}].map(pos =>
arr[pos.x][pos.y] = pos.value
)
console.log(arr)
I expected the code to give [[1,0,0],[2,0,0],[3,0,0]] but instead it give [[3,0,0],[3,0,0],[3,0,0]], in other words it draws all as last y (value 3) and ignore the [pos.x] for some reason, don't sure why.
I'd liked to get some help with a possible workaround as explanation why this code not working as I expecting
thanks in advance!
the problem is when you do the outer fill , that fill function is executed only once, so basically you are having reference to same array in the nested arrays, so when you map you keep updating that same reference and hence all are same in the end
you might wanna do
let arr = [];
for(let i = 0; i < 3; i++) { arr.push(Array(3).fill(0));}
Try this instead:
var arr = Array.from({length:3},()=>Array(3).fill(0));
[{x: 0, y: 0, value: 1}, {x: 1, y: 0, value: 2},{x: 2, y: 0, value: 3}].map(pos =>
arr[pos.x][pos.y] = pos.value
)
console.log(arr);
The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.
Related
This question already has answers here:
One-liner to take some properties from object in ES 6
(12 answers)
Closed 4 years ago.
I would like to create an new object from a bigger one, by copying only a few properties from it. All the solutions I know are not very elegant, I wonder if there is a better choice, native if possible (no additional function like at the end of the following code)?
Here is what I usually do for now:
// I want to keep only x, y, and z properties:
let source = {
x: 120,
y: 200,
z: 150,
radius: 10,
color: 'red',
};
// 1st method (not elegant, especially with even more properties):
let coords1 = {
x: source.x,
y: source.y,
z: source.z,
};
// 2nd method (problem: it pollutes the current scope):
let {x, y, z} = source, coords2 = {x, y, z};
// 3rd method (quite hard to read for such simple task):
let coords3 = {};
for (let attr of ['x','y','z']) coords3[attr] = source[attr];
// Similar to the 3rd method, using a function:
function extract(src, ...props) {
let obj = {};
props.map(prop => obj[prop] = src[prop]);
return obj;
}
let coords4 = extract(source, 'x', 'y', 'z');
One way to do it is through object destructuring and an arrow function:
let source = {
x: 120,
y: 200,
z: 150,
radius: 10,
color: 'red',
};
let result = (({ x, y, z }) => ({ x, y, z }))(source);
console.log(result);
The way this works is that the arrow function (({ x, y, z }) => ({ x, y, z })) is immediately called with source as the parameter. It destructures source into x, y, and z, and then immediately returns those as a new object.
You can do it like below via Spread Operator
let source = {
x: 120,
y: 200,
z: 150,
radius: 10,
color: 'red',
};
let {radius, color, ...newObj} = source;
console.log(newObj);
Just take a function.
const extract = ({ x, y, z }) => ({ x, y, z });
let source = { x: 120, y: 200, z: 150, radius: 10, color: 'red' };
console.log(extract(source));
Another solution is a destructuring to a target object with target properties.
let source = { x: 120, y: 200, z: 150, radius: 10, color: 'red' },
target = {};
({ x: target.x, y: target.y, z: target.z } = source);
console.log(target);
IIFE with destructuring maybe?:
const coords = (({x, y, z}) => ({x, y, z}))(source);
1st method is elegant and readable.
Please don't obfuscate simple operations by some workarounds. Other people who will need to maintain this code, including future yourself will be very thankful in the future.
For simple cases like this the object destructuring mentioned in other answers is very neat but tends to look a bit cumbersome when dealing with larger structures as you double up on property names.
Expanding on your own answer - if you were going to write an extract utility (I'll roll my own for fun)... you can make it more flexible by currying it - allowing you to swap the order of the arguments (notably putting the data source last) while still being variadic in accepting property names.
I'd consider this signature: extract = (...props) => src => { ... } more elegant as it allows for a greater degree of reuse in composing new, named functions:
const extract = (...props) => src =>
Object.entries(src).reduce(
(obj, [key, val]) => (
props.includes(key) && (obj[key] = val),
obj
), {})
const getCoords = extract('x', 'y', 'z')
const source = {
x: 120,
y: 200,
z: 150,
radius: 10,
color: 'red'
}
console.log(getCoords(source))
You can try reduce over [x,y,z] array:
let source = {
x: 120,
y: 200,
z: 150,
radius: 10,
color: 'red',
};
const coords = ['x','y','z'].reduce((a,c) => Object.assign(a,{[c]: source[c]}), {});
console.log(coords);
I would like to be able to get and use the key of a selected object in js
Lets say I have the following object that contains other objects
verts = { A: {x: 7.5, y: 0, z: -7.5}, B: {x: 0, y: 0, z: -15 }
If I can access item A for example with the following;
console.log(verts.A)
It will show me the value within the object (i.e. x: 7.5, y: 0, z: -7.5) but I do not know how to access the selected objects key i.e. in this case "A". I would like to be able to store it as a variable for use as a string later on. It feels like I should be able to write this.key or this[key] somewhere somehow but I cannot find an appropriate answer on here. I am using jquery so if there is a quick way using that thank you.
Thanks for any advice as ever
Once you've read an object using a key, there is no longer a link back to the key you used.
The best thing you can do is store the key you're using in a variable and then use square bracket notation to read it:
var verts = { A: {x: 7.5, y: 0, z: -7.5}, B: {x: 0, y: 0, z: -15 } };
var key = 'A';
var result = verts[key];
console.log(key, result);
Another option is to run your initial object through a pre-processor to build this link:
function preProcess(input){
return Object.keys(input).reduce( function(p,c){
var newObj = input[c];
newObj._key = c;
p[c] = newObj
return p
},{});
}
var verts = { A: {x: 7.5, y: 0, z: -7.5}, B: {x: 0, y: 0, z: -15 } };
var vertsWithKeys = preProcess(verts);
var item = verts.A;
console.log(item._key, item);
You're making this more complicated than it has to be. If you know at some point which keys you're using (and it seems you do), then all you need to do is ensure that those keys are passed along to whatever it is that needs them.
Like this:
//vertices stored as objects
verts = { A: {x: 7.5, y: 0, z: -7.5}, B: {x: 0, y: 0, z: -15}, C: {x: 0, y: 0, z: -7.5} }
//make a triangle using accessed vertices
makeTriangle(verts, 'A', 'B', 'C')
function makeTriangle(vertices, key1, key2, key3){
$("example").append('\
<a-triangle\
id="' + key1 + '_'+ key2 + '_'+ key3 + '"\
vertex-a="' + vertices[key1](joined) + '"\
vertex-b="' + vertices[key2](joined) + '"\
vertex-c="' + vertices[key3](joined) + '"\
</a-triangle>');
}
I'm trying to make a match-3 game (candy crush like). I have an object level which has tiles property which is a 2d array. After I do some manipulations I want to change the type of a specific element to -1 using this simple line (I'll be using for, but for now I've made it simple for demonstrative purposes)
level.tiles[1][0].type = -1;
Here is the code
var level = {
x: 250, // X position
y: 113, // Y position
columns: 8, // Number of tile columns
rows: 8, // Number of tile rows
tilewidth: 40, // Visual width of a tile
tileheight: 40, // Visual height of a tile
tiles: [], // The two-dimensional tile array
selectedtile: {selected: false, column: 0, row: 0}
};
var tileTypes = [
{
type: "red",
colors: [255, 128, 128]
},
{
type: "green",
colors: [128, 255, 128]
},
{
type: "darkBlue",
colors: [128, 128, 255]
},
{
type: "yellow",
colors: [255, 255, 128]
}
];
function createLevel() {
for (var i = 0; i < level.columns; i++) {
level.tiles[i] = [];
}
for (var i = 0; i < level.columns; i++) {
for (var j = 0; j < level.rows; j++) {
level.tiles[i][j] = getRandomTile();
}
}
}
function getRandomTile() {
return tileTypes[Math.floor(Math.random() * tileTypes.length)];
}
createLevel();
level.tiles[1][0].type = -1;
Unfortunately not only tiles[1][0] is modified, but multiple cells. The interesting part is that every time random cells are affected
This occurs because getRandomTile() returns a reference to a tile type, not a copy of it.
I.e. to simplify this case:
var a = {x: 1};
var b = [a, a, a, a];
b[0].x = 2;
console.log(a, b);
will output
{x: 2} [{x: 2}, {x: 2}, {x: 2}, {x: 2}]
If you want the tiles to be modifiable, have getRandomTile return a copy – a shallow copy in this case, so colors is still a reference, not a copy – of the randomly chosen tile type.
function getRandomTile() {
const tileType = tileTypes[Math.floor(Math.random() * tileTypes.length)];
// Idiom for shallow copy, i.e. assign all properties of tileType
// into a new, unique object.
return Object.assign({}, tileType);
}
The problem is you modify the type object, instead of linking to another type. A solution would be to clone it when creating the tiles:
function getRandomTile() {
var srcType = tileTypes[Math.floor(Math.random() * tileTypes.length)];
return {type:srcType.type, colors:srcType.color};
}
Another one (depending on your goal) would be to have Tile objects, each one having a reference to a Type object (not just an integer). At this point some classes might be helpful:
class TileType {
constructor(colors){
this.colors = colors;
}
}
let tileTypes = [...]
class Tile {
constructor(){
this.type = tileTypes[Math.random()*tileTypes.length|0];
}
setNewType(type){
this.type = type;
}
}
etc.
This is caused by getRandomTile which returns the same reference of the object defined in tileTypes if the index passed in is the same. You can print tileTypes to help your understand what happens.
I want to mix two objects in JavaScript:
let a = {x: 1, y: 2, z:3};
let b = {x:10, y: 20};
let c = Object.assign(a, b);
This gives the correct value for c:
Object { x: 10, y: 20, z: 3 }
But now a has been modified too!
Object { x: 10, y: 20, z: 3 }
Is there a way to assign a onto b into a new object?
The first argument to assign is the target. So it's going to get changed. You can simply pass an empty object for your target if you don't want any of the sources to change:
let a = {x: 1, y: 2, z:3};
let b = {x:10, y: 20};
let c = Object.assign({},a, b);
console.log(c);
console.log(a); // a is unchanged
You could use the spread operator:
let a = {x: 1, y: 2, z: 3};
let b = {x: 10, y: 20};
let c = {
...a,
...b
}
console.log(c);
console.log(a);
Definitively the spread operator. It helps to add a single property, like styling CSS in JS. But be aware that it's currently only in stage 4 of EcmaScript.
const lessStyle = {
color: 'blue',
backgroundColor: 'yellow'
};
const moreStyle = {...lessStyle, color: 'red'};
// lessStyle is not affected
You can use it today in Typescript and JSX though.
let a = {x: 1, y: 2, z:3};
let b = {x:10, y: 20};
let c = Object.assign({}, a, b);
You need the {} within the assign method for the first object because if you read the documentation for Object.assign method here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Parameters It states that the first parameter is the target object and the rest are the sources. so right now you are assigning b to a and returning the new a to c. So if your first argument is an empty object this won't happen.
I need to format an array from a list of values.
Currently I have the following hard-coded points:
points = [
{x: 20, y: 112},
{x: 23, y: 101},
{x: 51, y: 89},
{x: 63, y: 89},
{x: 84, y: 129},
{x: 64, y: 153},
{x: 45, y: 151},
{x: 38, y: 140},
{x: 28, y: 150},
{x: 10, y: 144},
{x: 0, y: 130},
{x: 10, y: 114}
];
The resulting array is to be passed to a function.
I now need to pass another array to the same function but I cannot hard-coded them as above. Instead, I am using a JS framework to grab the points dynamically using, for example, $(#container).get('points');
How do I convert the new array so that it is formatted similarly to the x: | y: structure as above?
points="20,112, 23,101, 51,89, 63,89, 84,129, 64,153, 45,151, 38,140, 28,150, 10,144, 0,130, 10,114"
I found the following in MooTools:
Array.each([1, 2, 3], function(number, index)
{
alert('x:' + number + ', y: ' + index);
});
...but somehow that doesn't seem like the correct way to do this.
Can I get a little guidance please?
You can split [docs] the string and iterate over it, taking two values in each iteration:
var parts = points.split(',');
var pointsArray = [];
for(var i = 0, l = parts.length; i < l; i += 2) {
pointsArray.push({x: +parts[i], y: +parts[i+1]});
}
You should actualy split it twice:
var points = "12,12, 1,2, 3,4"
var arr = points.split(', ');
for(var i = 0; i< arr.length; i++)
{
var point = arr[i].split(',');
document.write(point+ ' <br />' );
arr[i] = {x:point[0], y:point[1]};
document.write(' '+arr[i].x + ' ' + arr[i].y + ' <br/>');
}
Apart from that, just like the other comment.