Add Key To Javascript Array - javascript

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

Related

What is the best way to check multidimensional array in typescript or javascript to detect duplicate values?

I have two dimensional array like below:
array = [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ]
I want to compare value in array index to see if they have duplicate values. For example
array[0] = [1,1];
array[1] = [1,2];
array[2] = [1,1];
We can see that value at index 0 and 2 are same that is [1,1]. So, in that case I want to have true flag. What is the most efficient way to do it? or What are different ways to do it? Any kind of suggestion or help would be great with bit of explanation. Thanks in advance.
You can achieve it by convert the inner array elements into a string just for the comparison purpose.
Demo :
const arr = [[ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ]];
const stringConversion = arr.map((item) => JSON.stringify(item))
const duplicateElements = stringConversion.filter((item, index) => stringConversion.indexOf(item) !== index)
console.log(duplicateElements.length ? true : false);
So, what I think you can do is:
Cycle every element of the multidimensional array.
Then check if the two element are the same by accessing the "row" with the index 0 and index 1
I think you can use different way to loop the array, this is what I tried:
// DECLARATIONS
array = [[ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ]];
// LOOPING THE ARRAY
for (row of array)
{
// RETURN TO CONSOLE OR WHATEVER THE BOOLEAN VALUE
console.log(row[0] == row[1]);
}
String to convert array to a one-dimensional array of strings and some to check if any element is duplicated:
const arr = [[1, 1], [1, 2], [1, 1], [2, 3]];
const result = arr.map(String).some((v, i, a) => a.indexOf(v) !== i);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

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
}

append static elements in object to each object in array of objects javascript

How do I take this object and array.
const data = {
type: "hello",
point: 1.8
};
const raw = [
{
x: [1, 2],
y: [-1.1, -1.2]
},
{
x: [14, 24],
y: [-1.14, 1.24]
}
];
Then "append" the items in the data object to each object in the raw array. The desired end result is;
const result = [
{
x: [1, 2],
y: [-1.1, -1.2],
type: "hello",
point: 1.8
},
{
x: [14, 24],
y: [-1.14, 1.24],
type: "hello",
point: 1.8
}
];
I tried using map but this object works with arrays, then I looked at using Object.keys but am having no luck.
Use map with spreading:
const data = {type:"hello",point:1.8};
const raw = [{x:[1,2],y:[-1.1,-1.2]},{x:[14,24],y:[-1.14,1.24]}];
const result = raw.map(e => ({ ...e, ...data }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: auto; }
ES5 syntax:
var data = {type:"hello",point:1.8};
var raw = [{x:[1,2],y:[-1.1,-1.2]},{x:[14,24],y:[-1.14,1.24]}];
var result = raw.map(function(e) {
return Object.assign({}, e, data);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: auto; }
map is indeed the tool you want. I'd probably combine it with destructuring in the map callback parameter list and property spread in the result value:
const result = raw.map(({x, y}) => ({x, y, ...data}));
Live Copy:
const data = {
type: "hello",
point: 1.8
};
const raw = [
{
x: [1, 2],
y: [-1.1, -1.2]
},
{
x: [14, 24],
y: [-1.14, 1.24]
}
];
const result = raw.map(({x, y}) => ({x, y, ...data}));
console.log(result);
Note that if data had any properties whose values were objects (data in your example doesn't), using spread will copy only the references to the objects, it won't make deep copies. So all of your result objects should share them. You could deep copy if that were relevant.
I found a solution;
const data = {type:"hello",point:1.8};
const raw = [{x:[1,2],y:[-1.1,-1.2]},{x:[14,24],y:[-1.14,1.24]}];
const result = raw.map(r => Object.assign(r, data));
console.log(result);
Some feedback on this approach would be appreciated. Looking a the solutions provided now. Thank you all.

Convert array of values to array of objects (key-value) pairs in JavaScript

Is there a simple way to convert an array of values:
dataset = [5, 10, 13];
to an array of objects, wherein each object is a key-value pair?
dataset = [ { key: 0, value: 5 },
{ key: 1, value: 10 },
{ key: 2, value: 13 } ];
This example is an abbreviated version of the dataset in the "Data Join with Keys" section of Scott Murray's Interactive Data Visualization for the Web, 2nd ed, p. 187.
I had trouble finding an answer, and therefore I am posting my own solution below.
Iterate the array with Array.map(). Array.map() accepts a callback that returns a new item. The 1st param is the original item (value), the 2nd is the index (key):
const dataset = [5, 10, 13];
const result = dataset.map((value, key) => ({ key, value }));
console.log(result);
You can use the function map
var dataset = [5, 10, 13]
var result = dataset.map((n, i) => ({ key: i, value: n }))
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Another alternative, Array.from
var dataset = [5, 10, 13]
var result = Array.from(dataset, (n, i) => ({key: i, value: n}))
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

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.

Categories

Resources