Compare 2 array using lodash - javascript

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.

Related

Use reduce to remove object in an array

I am trying to return an array that contain of one of property.
So there is an array of objects like
[{x: 5, y: 607, width: 782, height: 602, line_width: 3, …},
{x: 10, y: 602, width: 772, height: 592, line_width: 3, …},
{x: 0, y: 400, size: 18, text: 'This cer..}, ..]
Some object has section: 'TextInstruction' property defined and some do not.
I am trying to return an array that is only containing section with no duplicate and no undefined.
So return ['TextInstruction', 'RectangleInstruction', ...]
No [undefined, 'TextInstruction', 'TextInstruction', ...]
Can anyone help me with JavaScript to get this using reduce() function?
You can try this:
var objectArray = {someting....}; // Your Object Array
var indexOfObject = objectArray.findIndex(object => {
return object.section == null;
});
objectArray.splice(indexOfObject, 1);
You don't need reduce to do that. You can do it with filter and map.
myArray
// filter missing sections
.filter(a => a.section)
// map to array of sections
.map(a => a.section)
// filter unique
.filter((a, i, arr) => arr.indexOf(a) === i)
The reduce() way of doing it could be something like this:
const data=[{a:12,b:45,section:"first"},{section:"second",d:5,f:7},{x:23,y:78,height:200},{a:445,x:34,section:"first"}];
const res1=Object.keys(data.reduce((a,c)=>{
if(c.section) a[c.section]=1;
return a;
}, {}));
// Or, using the es6 Set object:
const res2=[...data.reduce((a,c)=>{
if(c.section) a.add(c.section);
return a;
}, new Set())];
// show results:
console.log(res1,res2);
The second approach makes sense when the values to be collected are objects (and not only strings).

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
}

Javascript, dynamically create an empty object copy during a map

I'm struggling to find a good solution to process my array of objects.
I have two arrays:
let structure = ["horizontal","vertical","small","small","small"]
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"small","position":2},
{"id":9,"title":"xxxxx","format":"small","position":3},
{"id":11,"title":"xxxxx","format":"small","position":4}]
Edit: Items are more complex than this: it has about 15 attributes...
structure has a dynamic length and is my reference array. When I change structure I must remap the items array changing the format according to structure. So if I change structure to
let structure = ["horizontal","vertical","vertical","vertical","small"]
The array must change to
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"vertical","position":2},
{"id":9,"title":"xxxxx","format":"vertical","position":3},
{"id":11,"title":"xxxxx","format":"small","position":4}]
This can be done with a map.
This is my Vue method, I map the structure and use the function changeStructure I change the format.
methods: {
changeStructure(object,structure) {
object.format = structure
return object
},
updateCoverElements() {
let structure = this.coverTypes[this.currentCoverVersion]
let elements = this.coverElements
let changeStructure = this.changeStructure
let revisedElement = structure.map(function(structure, index) {
return changeStructure(elements[index],structure)
});
console.log(revisedElement);
}
},
But the problem is that, as I told before, structure has a dynamic length.
So when I change to
let structure = ["horizontal","vertical","vertical"]
Item results must be
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"vertical","position":2}]
This is not a problem, if the new structure length has less elements.
But when I change to
let structure = ["horizontal","vertical","vertical","vertical","vertical","vertical","vertical"]
Item results must be
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"vertical","position":2},
{"id":"","title":"","format":"vertical","position":3},
{"id":"","title":"","format":"vertical","position":4},
{"id":"","title":"","format":"vertical","position":5},
{"id":"","title":"","format":"vertical","position":6}]
And here is the problem: I cannot find a good way to dynamically create an object with the same identical structure as other items objects (a copy), with every field empty except for position, the index of the array, and format.
You could use the spread syntax like this. If items has a value at the index, it will overwrite the default id and title values.
let structure = ["horizontal","vertical","vertical","vertical","vertical","vertical","vertical"]
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"vertical","position":2}]
const defaultObj = { id: '', title: '' }
const newItems = structure.map((format, position) => {
return { ...defaultObj, ...items[position], format, position }
})
console.log(newItems)
Just slice off a new copy of items with max structure.length items, then iterate through your new clone of items and set each format attribute. Finally, create new objects for any elements in structure that don't have a corresponding partner in items:
var structure = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
var items = [
{'id':1,'title':'xxxxx','format':'horizontal','position':0},
{'id':3,'title':'xxxxx','format':'vertical', 'position':1},
{'id':6,'title':'xxxxx','format':'vertical', 'position':2},
];
// update all extant items
var _items = Object.assign([], items.slice(0, structure.length));
_items.forEach(function(i, idx) { i.format = structure[idx] });
// create any new items
for (var i=_items.length; i<structure.length; i++) {
_items.push(Object.assign({}, items[0], {
id: '',
title: '',
position: i,
format: structure[i],
}))
}
console.log(_items)
The best way to solve this problem using map() method would be to organize your implementation functional so that you could call it many times with a different set of data wherever you need (the concept of reusability).
Here is what I have tried. I have defined the function named getAlteredArray(items, structure) which returns the desired array. Note that if you are looking to use map() method means you want a new array (I mean you don't want to alter the passed array).
I have pasted the o/p on the code itself (it is commented out).
// function that creates new array with desired items and returns to the caller
function getAlteredArray(items, structure) {
let newArr = items.map((obj, index) => {
// obj => {"id":1,"title":"xxxxx","format":"horizontal","position":0}
obj["format"] = structure[index]
return obj
})
return newArr
}
// function that creates set of data needs to be passed to getAlteredArray() function
function test() {
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"small","position":2},
{"id":9,"title":"xxxxx","format":"small","position":3},
{"id":11,"title":"xxxxx","format":"small","position":4}]
// TEST 1 - Call getAlteredArray() with `items` & `structure`
let structure = ["horizontal","vertical","vertical","vertical","small"]
let newArr = getAlteredArray(items, structure)
console.log(newArr)
/*
[ { id: 1, title: 'xxxxx', format: 'horizontal', position: 0 },
{ id: 3, title: 'xxxxx', format: 'vertical', position: 1 },
{ id: 6, title: 'xxxxx', format: 'vertical', position: 2 },
{ id: 9, title: 'xxxxx', format: 'vertical', position: 3 },
{ id: 11, title: 'xxxxx', format: 'small', position: 4 } ]
*/
// TEST 2
let structure2 = ["horizontal","vertical","small","small","small"]
let newArr2 = getAlteredArray(items, structure2)
console.log(newArr2)
/*
[ { id: 1, title: 'xxxxx', format: 'horizontal', position: 0 },
{ id: 3, title: 'xxxxx', format: 'vertical', position: 1 },
{ id: 6, title: 'xxxxx', format: 'small', position: 2 },
{ id: 9, title: 'xxxxx', format: 'small', position: 3 },
{ id: 11, title: 'xxxxx', format: 'small', position: 4 } ]
*/
}
// Start
test()

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

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