Create array from points - javascript

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.

Related

Nested arrays manipulation weird behaviour, js

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.

Call function on each array indexs value

I have an array which looks like this
arcAxis:
0:{x: 1.2858791391047208e-15, y: 21}
1:{x: -21, y: 21.000000000000004}
2:{x: -35.8492424049175, y: 6.150757595082504}
3:{x: -39.40038395815852, y: -14.546812157640753}
4:{x: -32.12697787933814, y: -34.24700413672001}
5:{x: -16.811252024253655, y: -48.61462542668643}
6:{x: 3.0355856977321465, y: -55.47779032614515}
Now I have a function which draws elements using x and y of arcAxis.
What I want to do is to call that function to draw an element for each of arcAxis's index value something like this
function test() {
plot(0. x, 0. y)
}
.....
function test() {
plot(6. x, 6. y)
}
So, that I have 6 new elements made on different x,y values respective to their indexes
my approach is printing each element 6 times then printing next element 6 times
function test() {
const arcAxis = this.spiral();
for (var z in arcAxis) {
plot(arcAxis[z].x, arcAxis[z].x)
}
}
Anyway, can I print each element only 1 time with only 1 indexes value?
let data= {
arcAxis:[
{x: 1.2858791391047208e-15, y: 21},
{x: -21, y: 21.000000000000004},
{x: -35.8492424049175, y: 6.150757595082504},
{x: -39.40038395815852, y: -14.546812157640753},
{x: -32.12697787933814, y: -34.24700413672001},
{x: -16.811252024253655, y: -48.61462542668643},
{x: 3.0355856977321465, y: -55.47779032614515}
]
}
data.arcAxis.forEach(({x, y})=>{
plot(x,y);
})
function plot(x,y){
console.log("X: ", x,"Y: ", y );
}
If you are using a pre EcmaScript 6 version:
arcAxis.forEach(function(element) {
plot(element.x, element.y);
});
And for EcmaScript 6 and onwards:
arcAxis.forEach(element => plot(element.x, element.y));

How can I display the key of an accessed object in javascript

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

Is there an immutable version of Object.assign?

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.

Simple variable issue

I am trying to change my variables inside my items variable and not sure how to do it.
var items = [
{name: '#builder', x: 0, y:15},
{name: '#image', x: 0, y:15},
{name: '#button', x: -100, y: -55}
];
//I only want to change builder and image but not button...How to do this?
if(i>5){
items = [
{name: '#builder', x: 50, y:105},
{name: '#image', x: 110, y:115}
];
}
Thanks for the help.
Have you considered using an object hash table instead?
var items = {
'#builder' : { x: 0, y:15},
'#image': { x: 0, y:15},
'#button': {x: -100, y: -55}
};
Then you can change them like so:
items['#builder'].x = 50;
If it's not an option, that's cool, but it seems like if you want to look things up by name, this might be a better route for you.
Outside of that, you'd have to loop through each record to find the name you wanted and set the values appropriately.
var items = [
{name: '#builder', x: 0, y:15},
{name: '#image', x: 0, y:15},
{name: '#button', x: -100, y: -55}
];
function updateValues(name, x, y) {
for(var i = 0; i < items.length; i++) {
var item = items[i];
if(item.name == name) {
item.x = x;
item.y = y;
return;
}
}
}
updateValues('#builder', 50, 105);
If you know the position, then you could do:
if (i > 5) {
items[0].x = 50;
items[0].y = 105;
items[1].x = 110;
items[1].y = 115;
}

Categories