How to insert a object in an array (as a element ) - javascript

I am from C++ background.
I am trying to translate a C++ code to JavaScript.
in C++ we have vector < pair < int,int > > to store pairs.
in JS i have a situation. i want to store 2D coordinates. i actually want to push new coordinates to the array.
i did like
first I created a Object
const coordinate = {
x= 9,
y= 10
}
Then i tried to push that object into the array CoordinateStorage that i want this object to get stored
CoordinatesStorage.unshift({X : coordinate.x, Y : coordinates.y});
I know this code shown above is absolutely wrong to store an object into the array. I searched out for sources but i got nothing useful.
Please recommend some sources that i can refer for such translation related problems if possible.

Generally speaking, we should use the .push method for an array.
There are other methods available you can find them here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array but the .push method for your case is more suitable.
Basically, as a result, we want to have something like this:
[ {x: 2, y: 4 }, { x: 2, y: 4 } ] We have an array of objects.
Or we could also have an array of arrays:
[[1, 2], [3, 4], [4, 6]] Not sure if it okay for your case, but maybe as an option.
Also, we could create a class Vector and we might have something like
[ Vector { x: 1, y: 2 }, Vector { x: 3, y: 4 }, Vector { x: 4, y: 6 } ]
Let's take a look at the examples:
Using the plain object for the vector:
const coordinate1 = {
x: 2,
y: 4
};
const coordinate2 = {
x: 3,
y: 4
};
const coordinatesStorage = [];
coordinatesStorage.push(coordinate1);
coordinatesStorage.push(coordinate2);
If you will do console.log(coordinatesStorage) you will see [ { x: 2, y: 4 }, { x: 3, y: 4 } ]
Using the array to store a vector:
const coordinate1 = [1, 2];
const coordinate2 = [3, 4];
const coordinatesStorage = [];
coordinatesStorage.push(coordinate1);
coordinatesStorage.push(coordinate2);
The coordinatesStorage will be [ [ 1, 2 ], [ 3, 4 ] ]
Using the Vector class:
Maybe in your case, it would be more helpful to operate with a class Vector:
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const coordinatesStorage = [];
coordinatesStorage.push(new Vector(1, 2));
coordinatesStorage.push(new Vector(3, 4));
coordinatesStorage.push(new Vector(4, 6));
And here in the console you will see [ Vector { x: 1, y: 2 }, Vector { x: 3, y: 4}, Vector { x: 4, y: 6 } ]
Take a look at the Vector implementations in JS:
https://gist.github.com/jjgrainger/808640fcb5764cf92c3cad960682c677
https://github.com/maxkueng/victor/blob/master/index.js
I hope this helps. Good luck!

First initialize the array
var CoordinatesStorage = [];
//create object
const coordinate = {
x: 9, // Note - the operator is colon : not = as in the question
y: 10
}
// push to array
CoordinatesStorage.push(coordinate);
Now your array will be like this [{x:9, y:10}] if you push again the array will be [{x:9, y:10}, {x:9, y:10}]
Tip: Arrays are denoted by square brackets eg: ['math', 'science', 'english']
Objects are denoted by key-value pairs wrapped in curly brackets
eg: var student = {
name: "John", // string value
age: 6, // integer value
sex: "M",
phone: [123456789 , 564654654] // value is of array of 2 items
}

Related

FInd duplicates withtin array based on certain keys using lodash?

I have an array like this
let data = [{x:1,y:2,z:3},{x:1,y:2,z:3},{x:1,y:2,z:4},{x:11,y:2,z:3}]
Now I want to get only those items whose x,y,z values are the same.so expected output should be
{x:1,y:2,z:3}
Because {x:1,y:2,z:3} has duplicate values but rest of them not so I don't want to get rest of them because they do not have any duplicates. Please tell me how can I achieve this?
For lodash 4.17.15,
You can first use _.uniqWith and _.isEqual to find the unique values.
_.uniqWith(data, _.isEqual); // [{x:1,y:2,z:3},{x:1,y:2,z:4},{x:11,y:2,z:3}]
Then use _.difference to remove the unique values from the array, leaving just the duplicates
_.difference(data, _.uniqWith(data, _.isEqual)); // [{x:1,y:2,z:3}]
let data = [{x:1,y:2,z:3},{x:1,y:2,z:3},{x:1,y:2,z:4},{x:11,y:2,z:3},{x:11,y:2,z:3}]
function filterDuplicates(data) {
let dic = {};
data.forEach(obj => {
let strObj = JSON.stringify(obj, Object.keys(obj).sort());
if(strObj in dic) {
++dic[strObj];
return;
}
dic[strObj] = 0;
})
return Object.entries(dic).filter(([key, value]) => value > 0).map(([el]) => JSON.parse(el));
}
console.log(filterDuplicates(data));
Build an object to track the duplicates and use Object.values and filter
let data = [
{ x: 1, y: 2, z: 3 },
{ x: 1, y: 2, z: 3 },
{ x: 1, y: 2, z: 4 },
{ x: 11, y: 2, z: 3 },
];
const all = {};
data.forEach(({ x, y, z }) => {
const key = `x${x}y${y}z${z}`;
all[key] = key in all ? { x, y, z } : null;
});
const res = Object.values(all).filter(Boolean);
console.log(res);

Add Key To Javascript Array

I'm looking to append keys to the array which I have created, so I have an array of numbers:
var Array1 = [1, 2, 3, 4, 5];
I want to convert the array so it looks like this:
Array1 = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 4 }, { x: 5 }];
How do I append to each value in the array like so?
https://www.sitepoint.com/a-beginners-guide-to-data-binding-in-d3-js/ - Within this article, we can see they have an array called 'Data' - An array of objects. Now I have a simple array full of numbers and I need it to be converted as described above
You could use Array#map together with short hand properties for a new object for each element of the array.
var array = [1, 2, 3, 4, 5],
objects = array.map(x => ({ x }));
console.log(objects);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Array1 = Array1.map(entry => ({x: entry}));

Compare 2 array using lodash

I have 2 arrays of similar element but arranged in different order.
I have a source variable with is arranged according to arr1 based on key src and file of arr1 and source.
Now i want to arranged destination variable according to arr2.
Could you please let me know how we can done with lodash?
arr1 = [{x:0,y:1,src:a1},{x:1,y:1,src:b1},{x:2,y:1,src:c1}]
arr2 = [{x:1,y:1,src:b1},{x:1,y:1,src:a1},{x:1,y:1,src:c1}]
source = [{file:a1},{file:b1},{file:c1}]
Destination = [{file:b1},{file:a1},{file:c1}]
You could use lodash's map routine to achieve this:
let source = [{
x: 1,
y: 1,
src: 'b1'
}, {
x: 1,
y: 1,
src: 'a1'
}, {
x: 1,
y: 1,
src: 'c1'
}]
let destination = _.map(source, value => {
return { file: value['src']}
})
See here for an example.
Also note that you can achieve this using the standard JavaScript map function.

Create one array from 2 Arrays with keys x & y

I have 2 Arrays xDates and yMentions
xDates
[1453766400000, 1453852800000, 1453939200000...
yMentions
[5160, 5240, 7090...
Goal is an Array like so:
[
{
x: 1453766400000,
y: 5160
},
...
]
Trying to use Ramda Zip thought zipObj would be what I need, but the following produces just 1 object:
R.zipObj(['x', 'x', 'x'], [1, 2, 3]); => {"x": 3}
Figured perhaps I run R.zipObj on the x then the y arrays, then zip them together then set that as the Array for mentionsPointsArray below:
const createMentionPoints = (frequencyPoints, termsData) => {
const yMentions = termsData.mentions;
const propX = R.prop('x');
const xPointsFromFrequency = R.map(propX, frequencyPoints);
console.log('xDates', xPointsFromFrequency)
console.log('yMentions', yMentions)
const mentionsPointsArray = []
return frequencyPoints;
};
You should use Array#map function.
The map() method creates a new array with the results of calling a provided function on every element in this array.The provided function is a callback.
The elements from the result array are objects, like this: {"x":item, "y":yMentions[i]}.
var xDates=[1453766400000, 1453852800000, 1453939200000];
var yMentions=[5160, 5240, 7090];
console.log(xDates.map(function(elem,i){
return {"x":elem,"y":yMentions[i]}
}));
The ramda solution http://ramdajs.com/docs/#zipWith
var createPoints = (x, y) => {
return { x: x, y: y }
};
R.zipWith(createPoints, [1, 2, 3], ['a', 'b', 'c']);
// returns: [{"x": 1, "y": "a"}, {"x": 2, "y": "b"}, {"x": 3, "y": "c"}]
I think the cleanest point-free version would be:
const data1 = ['a', 'b', 'c']
const data2 = [1, 2, 3]
R.zipWith(R.objOf, data1, data2)
Please have a look at a working REPL here

Convert Js Array to JSON object with keys

I want to use the same object for jQplot and a library built on jQtable.
jQplot is fine with arrays but jQtable's library needs an named object (dictionary).
vals =
[
[1, 2],
[3,5.12],
[5,13.1],
[7,33.6],
[9,85.9],
[12,54],
[11,219.9]
];
This is my js array
I want it to be like
{
data: [{
X: 1,
Y: 2
},
{
X: 3,
Y: 5.12
},
{
X: 5,
Y: 13.1
}]
}
How to convert js array into named JSON array of objects? Are there any built in methods or I define my own method to read up that array and create a String for JSON?
var array = vals.map(function(val) {
return {
X : val[0],
Y : val[1]
};
});
var data = Object.keys(vals).map(function(key) {
return {X : vals[key][0], Y : vals[key][1]};
});

Categories

Resources