Update value of object with values in different array - javascript

I have two array with below structure:
Array1:
[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
Array2:
[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
result
Array1 =[{id:1234,name:"macaron",quantity:"330gm",rate:"300"},{id:5678,name:"Gelato",quantity:"450gm",rate:"500"}]
I want to be able to update the only rates of objects in Array1 with rate of objects in Array2.

If order or lengths of the arrays are different one efficient way is
create a Map of the new rates from Array2 then loop over Array1 ant get() from the Map.
This way you only iterate Array2 once instead of using multiple iterations of methods like find()
let Array1=[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}],
Array2=[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}];
const rateMap = new Map(Array2.map(({id, rate})=> [id, rate]));
Array1.forEach(e=> rateMap.has(e.id) && (e.rate = rateMap.get(e.id )))
console.log(Array1)

let Array1 = [
{id:1234,name:"macaron",quantity:"330gm",rate:"100"},
{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}
];
let Array2 = [
{id:1234,name:"macaron",quantity:"600gm",rate:"300"},
{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}
];
for (i = 0; i < Array1.length ; i++) {
Array1[i].rate = Array2[i].rate
}
console.log(Array1)

Array1 = Array1.map(item => {
return { ...item, rate: Array2.filter(rec => rec.id === item.id)[0].rate };
});
});

The cleanest solution I came up with.
But as charlietfl said: I make assumtion that both lengths are the same and in same order
let array1 = [{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
let array2 = [{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
array1.updateRate = function(array2) {
for(let i = 0; i < this.length;i++) {
console.log(this[i].rate)
this[i].rate = array2[i].rate;
console.log(this[i].rate)
}
}
array1.updateRate(array2);
console.log(array1)
Here is second (full) solution, where that asumption isn't made:
let array1 = [{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
let array2 = [{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
array1.updateRate = function(array2) {
for(let i = 0; i < this.length;i++) {
for(let j = 0; j < array2.lenght;j++) {
if(this[i].id === array2[j].id) {
this[i].rate = array2[j].rate;
break;
}
}
}
}
array1.updateRate(array2);
console.log(array2)

Related

Filter if array include an element of another array

I have two arrays like:
arr1 = ["orange","banana"]
arr2 = [{"fruit"= ["pineapple","banana"]},{"fruit"= ["grapes","apple"]},{"fruit"= ["apple","orange"]}]
And i need to filter if in second array exists an item of the first.
I am trying to do this:
let kFilter = arr1.map(itemY => { return itemY; });
let filteredK = arr2.filter(itemX => kFilter.includes(itemX.fruit));
But no success :-(
First to avoid too much iteration convert the simple array to an object something like following. Otherwise the complexity will be high
const fruitMap = {
"orange": 1,
"banana": 1
};
Then you have to iterate over each of the items in second array
arr2.forEach(fruitsObj => {
let arr = fruitsObj['fruit'];
for (let i = 0; i < arr.length(); i ++) {
if (fruitMap[arr[i]]) {
arr.splice(i, 1);
}
}
})
//declaration variables correctly
let arr1 = ["orange","banana"]
let arr2 = [{"fruit" : ["pineapple","banana"]},{"fruit" : ["grapes","apple"]},{"fruit": ["apple","orange"]}];
//filter using reduce
arr2.filter((e)=>arr1.reduce((a,i)=>a||e["fruit"].includes(i),false))
//filter using some
arr2.filter((e)=>arr1.some((i)=>e["fruit"].includes(i)))

What is the best optimize way to check if array of arrays contains another array in JavaScript?

I am trying to find an optimized way to check if an array of arrays contains another array.
Example:
const result = [['a','b','c'],['d']];
const sample = ['d'];
Here, result contains an array that matches sample array. How to optimize a two for loop solution with a length check?
for(let i = 0 ; i <result.length; i ++){
let arr = result[i];
if(arr.length === sample.length){
for(let j = 0 ; j <sample.length; j ++){
if(arr[j] !== sample[j]){
return false;
}
}
return true;
}
}
Looking for a faster way.
You could simply do,
const result = [
['a', 'b', 'c'],
['d']
];
const sample = ['d'];
const sample2 = ['a', 'b'];
console.log(result.some(r => JSON.stringify(r) == JSON.stringify(sample)))
console.log(result.some(r => JSON.stringify(r) == JSON.stringify(sample2)))

Comparing array (start with option) by giving another array in JavaScript

I have two arrays;selectedFunction say array1. with these values
['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001']
and allFunctions say array2. with these values ;
[ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ]
if element in array1 starts with the given element from array2, then push that element of array1 into myFinalSelectedFunctions[] say array3. In above arrays, 2nd and 3rd elements of array1 should be pushed into array3. How to perform such task in javascript/Nodejs ? I have basic knowledge of javascript, not an expert.
You can use .filter() with .some() to return true if a hex code from array1 .startsWith() a hex code in array2:
const array1 = ['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001'];
const array2 = [ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ];
const res = array1.filter(hex => array2.some(code => hex.startsWith(code)));
console.log(res);
Yo can do following:
const arr1 = ['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001'];
const arr2 = [ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ]
const arr3 = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if (arr1[i].startsWith(arr2[j])) {
arr3.push(arr1[i])
}
}
}
console.log(arr3)
Answer by #nick-parsons is much cleaner. You can go for it.

Unsplit two arrays Javascript

I have the following code
var Louis = [ 'Louis.IX', 'Louis.VIII' ]
var array1 = [];
var array2 = [];
for (var i = 0; i < Louis.length; i++) {
var split = Louis[i].split(".");
array1.push(split[0]); // before the dot
array2.push(split[1]); // after the dot
}
console.log("Louisname", array1);
console.log("Louisnum", array2);
and the output is
Louisname [ 'Louis', 'Louis' ]
Louisnum [ 'IX', 'VIII' ]
Now any idea on how can i revert the output into the initial array? Please help me, thanks.
You can use .map() with its second index argument to join elements in the first array with the second array by returning a string which contains elements in both arrays like so:
const array1 = ["Louis", "Louis"];
const array2 = ["IX","VIII"];
const original = array1.map((v, i) => `${v}.${array2[i]}`);
console.log(original);
If you're new to JS, here is a more straightforward/imperative way of achieving the same result (see code comments for details):
const array1 = ["Louis", "Louis"];
const array2 = ["IX","VIII"];
const original = [];
for(let i = 0; i < array1.length; i++) { // loop through all elements in array 1
const original_str = array1[i] + "." + array2[i]; // join array element `i` in array1 with array element `i` in array2
original.push(original_str); // add the joined string to the `original` array
}
console.log(original);

How to merge two json object values by id with plain Javascript (ES6)

I have two arrays of Javascript Objects and want to merge the properties of the two Javascript Objects with identical "ObjID" into one Javascript Object.
For example:
// Array of Javascript Objects 1:
let request1 = [{"ObjId":174864,"ObjMutationD":"2010-07-09T00:00:00.000Z","ObjMitarbeiterS":"epf","ObjAufId":142},
{"ObjId":175999,"ObjMutationD":"2010-07-09T00:00:00.000Z","ObjMitarbeiterS":"epf","ObjAufId":149}]
// Array of Javascript Objects 2:
let request2 = [{"ObjId":174864,"MulPfadS":"M:\\Originalbilder\\FGS\\95nn","MulDateiS":"9576.305-034-1","MulExtentS":"jpg"},
{"ObjId":177791,"MulPfadS":"M:\\Originalbilder\\FGS\\95nn","MulDateiS":"9576.305-035-1","MulExtentS":"jpg"}]
Merge into one Javascript object with the values of the same ObjId (see ObjID: 174864) and the rest (of the Objects) stays untouched:
let result = [{"ObjId":174864,"ObjMutationD":"2010-07-09T00:00:00.000Z","ObjMitarbeiterS":"epf","ObjAufId":142,
"MulPfadS":"M:\\Originalbilder\\FGS\\95nn","MulDateiS":"9576.305-034-1","MulExtentS":"jpg"},
{"ObjId":175999,"ObjMutationD":"2010-07-09T00:00:00.000Z","ObjMitarbeiterS":"epf","ObjAufId":149},
{"ObjId":177791,"MulPfadS":"M:\\Originalbilder\\FGS\\95nn","MulDateiS":"9576.305-035-1","MulExtentS":"jpg"}]
What I tried so far:
let request1 = [{"ObjId":174864,"ObjMutationD":"2010-07-09T00:00:00.000Z","ObjMitarbeiterS":"epf","ObjAufId":142},
{"ObjId":175999,"ObjMutationD":"2010-07-09T00:00:00.000Z","ObjMitarbeiterS":"epf","ObjAufId":149}]
let request2 = [{"ObjId":174864,"MulPfadS":"M:\\Originalbilder\\FGS\\95nn","MulDateiS":"9576.305-034-1","MulExtentS":"jpg"},
{"ObjId":177791,"MulPfadS":"M:\\Originalbilder\\FGS\\95nn","MulDateiS":"9576.305-035-1","MulExtentS":"jpg"}]
function joinObjects() {
var idMap = {};
for(let i = 0; i < arguments.length; i++) {
for(let j = 0; j < arguments[i].length; j++) {
let currentID = arguments[i][j]['ObjId'];
if(!idMap[currentID]) {
idMap[currentID] = {};
}
// Iterate over properties of objects in arrays
for(key in arguments[i][j]) {
idMap[currentID][key] = arguments[i][j][key];
}
}
}
// push properties of idMap into an array
let newArray = [];
for(property in idMap) {
newArray.push(idMap[property]);
}
return newArray;
}
let result = joinObjects(request1, request2);
You could use Map and Object.assign for merging the objects.
var request1 = [{
ObjId: 174864,
ObjMutationD: "2010-07-09T00:00:00.000Z",
ObjMitarbeiterS: "epf",
ObjAufId: 142
}, {
ObjId: 175999,
ObjMutationD: "2010-07-09T00:00:00.000Z",
ObjMitarbeiterS: "epf",
ObjAufId: 149
}],
request2 = [{
ObjId: 174864,
MulPfadS: "M:\\Originalbilder\\FGS\\95nn",
MulDateiS: "9576.305-034-1",
MulExtentS: "jpg"
}, {
ObjId: 177791,
MulPfadS: "M:\\Originalbilder\\FGS\\95nn",
MulDateiS: "9576.305-035-1",
MulExtentS: "jpg"
}];
var result = [...[request1, request2].reduce((m, a) => (a.forEach(o => m.has(o.ObjId) && Object.assign(m.get(o.ObjId), o) || m.set(o.ObjId, o)), m), new Map).values()];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can achieve this using Lodash _.merge function.
// Array of Javascript Objects 1:
let request1 = [{"ObjId":174864,"ObjMutationD":"2010-07-09T00:00:00.000Z","ObjMitarbeiterS":"epf","ObjAufId":142},
{"ObjId":175999,"ObjMutationD":"2010-07-09T00:00:00.000Z","ObjMitarbeiterS":"epf","ObjAufId":149}]
// Array of Javascript Objects 2:
let request2 = [{"ObjId":174864,"MulPfadS":"M:\\Originalbilder\\FGS\\95nn","MulDateiS":"9576.305-034-1","MulExtentS":"jpg"},
{"ObjId":177791,"MulPfadS":"M:\\Originalbilder\\FGS\\95nn","MulDateiS":"9576.305-035-1","MulExtentS":"jpg"}]
var merged = _.merge(_.keyBy(request1, 'ObjId'), _.keyBy(request2, 'ObjId'));
var result = _.values(merged);
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.10/lodash.min.js"></script>
in ES6 the spread operator will do that for you
var merged = {...request1[0], ...request2[0]};
More info here:
https://davidwalsh.name/merge-objects
You can do like this.
var merged = request1.map((x,i) => {
return {... request1[i],... request2[i]}
})

Categories