Compare 2 different Arrays by ID and calculate difference - javascript

I got 2 arrays
ArrayA = {"data":{"PlayerList":[{"Platform":1,"PlayerExternalId":205288,"Price":250,"RemainingTime":22},{"Platform":1,"PlayerExternalId":205753,"Price":10000,"RemainingTime":22}]}}
ArrayB = {"datafut": [{"currentPricePs4": "4149000","currentPriceXbox": "3328000","PlayerExternalId": "151152967"},{"currentPricePs4": "3315000","currentPriceXbox": "2720000","PlayerExternalId": "151198320"}]}
ArrayB is like a small database to compare prices. ArrayA needs theoretically an Interception with ArrayB. But this creates a new ArrayC which is complicated for me because I need the index of the results from ArrayA.
Moreover when comparing both array IDs, I need to compare both prices and calculate a difference into a variable so I can work with it later. How can I achieve this?
This is my pseudo code. Idk if this is even the right way..
Filter ArrayB by ArrayA //by playerID
for(
NewPrice = ArrayA.price / ArrayB.price + Index of ArrayA.price
index = Index of ArrayA.price)
Edit: or could I append the price from arrayB to arrayA and can calculate then somehow?

You can pass both arrays to following function: I have stored index, now if you only need index, you don't need to sort it otherwise I am sorting it on the base of index to keep the original order.
function mergeArrays(arrayA, arrayB) {
var players = arrayA.data.PlayerList;
var data = arrayB.data;
var arrayC = [];
for(let i=0; i<data.length; i++) {
var playerId = data[i].PlayerExternalId;
for(let j=0; j<players.length; j++) {
if(players[j].PlayerExternalId != playerId) {
continue;
}
var obj = {};
obj.playerId = playerId;
obj.index = j;
obj.price = players[j].price;
obj.xboxprice = data[i].currentPriceXbox;
obj.ps4price = data[i].currentPricePs4;
arrayC.push(obj);
}
}
arrayC.sort((a,b) => (a.index < b.index)?-1:(a.index>b.index?1:0));
return arrayC;
}

Related

push more than one elements at same index in array

how to push more than one element at one index of a array in javascript?
like i have
arr1["2018-05-20","2018-05-21"];
arr2[5,4];
i want resulted 4th array to be like:
arr4[["2018-05-20",5],["2018-05-21",4]];
tried pushing like this:
arr1.push("2018-05-20","2018-05-21");
arr1.push(5,4);
and then finally as:
arr4.push(arr1);
But the result is not as expected. Please someone help.
Actually i want to use this in zingChart as :
Options Data
Create an options object, and add a values array of arrays.
Calendar Values
In each array, provide the calendar dates with corresponding number values in the following format.
options: {
values: [
['YYYY-MM-DD', val1],
['YYYY-MM-DD', val2],
...,
['YYYY-MM-DD', valN]
]
}
Your question is not correct at all, since you cannot push more than one element at the same index of an array. Your result is a multidimensional array:
[["2018-05-20",5],["2018-05-21",4]]
You have to create a multidimensional array collecting all your data (arrAll)
Then you create another multidimensional array (arrNew) re-arranging previous data
Try the following:
// Your Arrays
var arr1 = ["2018-05-20","2018-05-21"];
var arr2 = [5, 4];
//var arr3 = [100, 20];
var arrAll = [arr1, arr2];
//var arrAll = [arr1, arr2, arr3];
// New Array definition
var arrNew = new Array;
for (var j = 0; j < arr1.length; j++) {
var arrTemp = new Array
for (var i = 0; i < arrAll.length; i++) {
arrTemp[i] = arrAll[i][j];
if (i === arrAll.length - 1) {
arrNew.push(arrTemp)
}
}
}
//New Array
Logger.log(arrNew)
Assuming the you want a multidimensional array, you can put all the input variables into an array. Use reduce and forEach to group the array based on index.
let arr1 = ["2018-05-20","2018-05-21"];
let arr2 = [5,4];
let arr4 = [arr1, arr2].reduce((c, v) => {
v.forEach((o, i) => {
c[i] = c[i] || [];
c[i].push(o);
});
return c;
}, []);
console.log(arr4);

Find common objects in multiple arrays by object ID

I've searched SO for a way to do this but most questions only support two arrays (I need a solution for multiple arrays).
I don't want to compare exact objects, I want to compare objects by their ID, as their other parameters may differ.
So here's the example data:
data1 = [{'id':'13','name':'sophie'},{'id':'22','name':'andrew'}, etc.]
data2 = [{'id':'22','name':'mary'},{'id':'85','name':'bill'}, etc.]
data3 = [{'id':'20','name':'steve'},{'id':'22','name':'john'}, etc.]
...
I'd like to return all objects whose ID appears in all arrays, and I don't mind which of the set of matched objects is returned.
So, from the data above, I'd expect to return any one of the following:
{'id':'22','name':'andrew'}
{'id':'22','name':'mary'}
{'id':'22','name':'john'}
Thanks
First, you really need an array of arrays - using a numeric suffix is not extensible:
let data = [ data1, data2, ... ];
Since you've confirmed that the IDs are unique within each sub array, you can simplify the problem by merging the arrays, and then finding out which elements occur n times, where n is the original number of sub arrays:
let flattened = data.reduce((a, b) => a.concat(b), []);
let counts = flattened.reduce(
(map, { id }) => map.set(id, (map.get(id) || 0) + 1), new Map()
);
and then you can pick out those objects that did appear n times, in this simple version they'll all come from the first sub array:
let found = data[0].filter(({ id }) => counts.get(id) === data.length);
Picking an arbitrary (unique) match from each sub array would be somewhat difficult, although picking just one row of data and picking the items from that would be relatively easy. Either would satisfy the constraint from the question.
If you want the unique object by Name
data1 = [{'id':'13','name':'sophie'},{'id':'22','name':'mary'}]
data2 = [{'id':'26','name':'mary'},{'id':'85','name':'bill'}]
data3 = [{'id':'29','name':'sophie'},{'id':'22','name':'john'}]
flattened = [ ...data1, ...data2, ...data3 ];
counts = flattened.reduce(
(map, { name }) => map.set(name, (map.get(name) || 0) + 1), new Map()
);
names = []
found = flattened.filter(({ name }) => {
if ((counts.get(name) > 1) && (!names.includes(name))) {
names.push(name);
return true
}
return false
});
its too many loops but , if u can find the common id which is present in all the arrays then it would make your finding easier i think .you can have one array value as reference to find the common id
var global = [];
for(var i = 0;i<data1.length;i++){
var presence = true;
for(var j=0;j<arrays.length;j++){
var temp = arrays[j].find(function(value){
return data1[i].id == value.id;
});
if(!temp){
presence = false;
break;
}
}
if(presence){
global.push(data1[i].id)
}
}
console.log(global);
var data1 = [{'id':'13','name':'sophie'},{'id':'22','name':'andrew'}];
var data2 = [{'id':'22','name':'mary'},{'id':'85','name':'bill'}];
var data3 = [{'id':'20','name':'steve'},{'id':'22','name':'john'}];
var arrays = [data1, data2, data3];
var global = [];
for(var i = 0;i<data1.length;i++){
var presence = true;
for(var j=0;j<arrays.length;j++){
var temp = arrays[j].find(function(value){
return data1[i].id == value.id;
});
if(!temp){
presence = false;
break;
}
}
if(presence){
global.push(data1[i].id)
}
}
console.log(global);
There's mention you you need n arrays, but also, given that you can:
put all the arrays into an array called data
you can:
combine your arrays
get a list of duplicated IDs (via sort by ID)
make that list unique (unique list of IDs)
find entries in the combined list that match the unique IDs
where the count of those items match the original number of arrays
Sample code:
// Original data
var data1 = [{'id':'13','name':'sophie'},{'id':'22','name':'andrew'}]
var data2 = [{'id':'22','name':'mary'},{'id':'85','name':'bill'}]
var data3 = [{'id':'13','name':'steve'},{'id':'22','name':'john'}]
var arraycount = 3;
// Combine data into a single array
// This might be done by .pushing to an array of arrays and then using .length
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort?v=control
var data = [].concat(data1).concat(data2).concat(data3);
//console.log(data)
// Sort array by ID
// http://stackoverflow.com/questions/840781/easiest-way-to-find-duplicate-values-in-a-javascript-array
var sorted_arr = data.slice().sort(function(a, b) {
return a.id - b.id;
});
//console.log(sorted_arr)
// Find duplicate IDs
var duplicate_arr = [];
for (var i = 0; i < data.length - 1; i++) {
if (sorted_arr[i + 1].id == sorted_arr[i].id) {
duplicate_arr.push(sorted_arr[i].id);
}
}
// Find unique IDs
// http://stackoverflow.com/questions/1960473/unique-values-in-an-array
var unique = duplicate_arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
});
//console.log(unique);
// Get values back from data
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?v=control
var matches = [];
for (var i = 0; i < unique.length; ++i) {
var id = unique[i];
matches.push(data.filter(function(e) {
return e.id == id;
}))
}
//console.log(matches)
// for data set this will be 13 and 22
// Where they match all the arrays
var result = matches.filter(function(value, index, self) {
return value.length == arraycount;
})
//console.log("Result:")
console.log(result)
Note: There's very likely to be more efficient methods.. I've left this in the hope part of it might help someone
var arr1 = ["558", "s1", "10"];
var arr2 = ["55", "s1", "103"];
var arr3 = ["55", "s1", "104"];
var arr = [arr1, arr2, arr3];
console.log(arr.reduce((p, c) => p.filter(e => c.includes(e))));
// output ["s1"]

How to create key value pair using two arrays in JavaScript?

I have two arrays, keys and commonkeys.
I want to create a key-value pair using these two arrays and the output should be like langKeys.
How to do that?
This is array one:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
This is array two:
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
This is the output I need:
var langKeys = {
'en-*': 'en_US',
'es-*': 'es_ES',
'pt-*': 'pt_PT',
'fr-*': 'fr_FR',
'de-*': 'de_DE',
'ja-*': 'ja_JP',
'it-*': 'it_IT',
'*': 'en_US'
};
You can use map() function on one array and create your objects
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];
var output = keys.map(function(obj,index){
var myobj = {};
myobj[commonKeys[index]] = obj;
return myobj;
});
console.log(output);
JavaScript is a very versatile language, so it is possible to do what you want in a number of ways. You could use a basic loop to iterate through the arrays, like this:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
var i;
var currentKey;
var currentVal;
var result = {}
for (i = 0; i < keys.length; i++) {
currentKey = commonKeys[i];
currentVal = keys[i];
result[currentKey] = currentVal;
}
This example will work in all browsers.
ES6 update:
let commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
let keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT', 'en_US'];
let zipArrays = (keysArray, valuesArray) => Object.fromEntries(keysArray.map((value, index) => [value, valuesArray[index]]));
let langKeys = zipArrays(commonKeys, keys);
console.log(langKeys);
// let langKeys = Object.fromEntries(commonKeys.map((val, ind) => [val, keys[ind]]));
What you want to achieve is to create an object from two arrays. The first array contains the values and the second array contains the properties names of the object.
As in javascript you can create new properties with variales, e.g.
objectName[expression] = value; // x = "age"; person[x] = 18,
you can simply do this:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];
var langKeys = {};
var i;
for (i=0; i < keys.length; i++) {
langKeys[commonKeys[i]] = keys[i];
}
EDIT
This will work only if both arrays have the same size (actually if keys is smaller or same size than commonKeys).
For the last element of langKeys in your example, you will have to add it manually after the loop.
What you wanted to achieve was maybe something more complicated, but then there is missing information in your question.
Try this may be it helps.
var langKeys = {};
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
function createArray(element, index, array) {
langKeys[element]= keys[index];
if(!keys[index]){
langKeys[element]= keys[index-(commonKeys.length-1)];
}
}
commonKeys.forEach(createArray);
console.info(langKeys);
Use a for loop to iterate through both of the arrays, and assign one to the other using array[i] where i is a variable representing the index position of the value.
var keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT'];
var commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
var langKeys = {};
for (var i = 0; i < keys.length; i++) {
var commonkey = commonKeys[i];
langKeys[commonkey] = keys[i];
}
console.log(JSON.stringify(langKeys));
let keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT'];
let commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
// declaration of empty object where we'll store the key:value
let result = {};
// iteration over first array to pick up the index number
for (let i in keys) {
// for educational purposes, showing the number stored in i (index)
console.log(`index number: ${i}`);
// filling the object with every element indicated by the index
// objects works in the basis of key:value so first position of the index(i)
// will be filled with the first position of the first array (keys) and the second array (commonKeys) and so on.
result[keys[i]] = commonKeys[i];
// keep in mind that for in will iterate through the whole array length
}
console.log(result);

Remove data from an array comparing it to an other array

I am trying to compare the items in "item" array and the copyofOpList array to retrieve the data occurrences in copyofOpList
this is my try:
var _deleteUsedElement1 = function(item) {
for (var i = 0; i < item.length-1; i++){
for (var j = 0; j< $scope.copyofOpList.length-1; j++){
if (item[i].operationCode == $scope.copyofOpList[j].code) {
$scope.copyofOpList.splice(j, 1);
} } } };
$scope.compareArrays = function() {
...Get data from web Service
_deleteUsedElement1(item);
}
the copyofOpList array has 14 elements,and the item array has 2 array
but my code deletes only one occurrence (the first),so please how can I correct my code,to retrieve any occurances in the copyofOpList array comparing to the item array
thanks for help
I'd try to avoid looping inside a loop - that's neither a very elegant nor a very efficient way to get the result you want.
Here's something more elegant and most likely more efficient:
var item = [1,2], copyofOpList = [1,2,3,4,5,6,7];
var _deleteUsedElement1 = function(item, copyofOpList) {
return copyofOpList.filter(function(listItem) {
return item.indexOf(listItem) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [3,4,5,6,7]
}
And since I just noticed that you're comparing object properties, here's a version that filters on matching object properties:
var item = [{opCode:1},{opCode:2}],
copyofOpList = [{opCode:1},{opCode:2},{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}];
var _deleteUsedElement1 = function(item, copyofOpList) {
var iOpCodes = item.map(function (i) {return i.opCode;});
return copyofOpList.filter(function(listItem) {
return iOpCodes.indexOf(listItem.opCode) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}]
Another benefit of doing it in this manner is that you avoid modifying your arrays while you're still operating on them, a positive effect that both JonSG and Furhan S. mentioned in their answers.
Splicing will change your array. Use a temporary buffer array for new values like this:
var _deleteUsedElement1 = function(item) {
var _temp = [];
for (var i = 0; i < $scope.copyofOpList.length-1; i++){
for (var j = 0; j< item.length-1; j++){
if ($scope.copyofOpList[i].code != item[j].operationCode) {
_temp.push($scope.copyofOpList[j]);
}
}
}
$scope.copyofOpList = _temp;
};

Sort Array in special manner

I have a problem sorting an array. I am not the smartest concerning these sort algorithms.
The array should have following structure:
var arr = [
[week, IssuesPriority1, IssuesPriority2, IssuesPriority3],
[week, IssuesPriority1, IssuesPriority2, IssuesPriority3],
[week, IssuesPriority1, IssuesPriority2, IssuesPriority3],
...
];
So for each week there is a number of issues for the priority very high, high, medium.
The string that needs to be parsed in this structure is following:
var string =
"26|3|1,27|6|1,28|7|1,29|2|1,30|2|1,31|2|1,32|2|1,33|3|1,
35|1|1,34|2|1,36|0|1,37|0|1,38|1|1,26|11|2,27|10|2,28|9|2,
29|13|2,30|10|2,31|8|2,32|10|2,33|12|2,34|14|2,35|11|2,
36|11|2,37|12|2,38|14|2,27|17|3,26|13|3,29|26|3,28|21|3,30|25|3,
31|20|3,34|30|3,32|18|3,33|25|3,35|33|3,36|28|3,38|28|3,37|27|3";
var arr = string.split(",");
for(var i = 0; i < arr.length; i++){
var currentArr = arr[i].split("|");
var week = currentArr[0];
var issues = currentArr[1];
var priority = currentArr[2];
}
I have a lack of ideas sorting it in the desired way. Can you help me?
I don't think you want any sorting at all. You are looking for grouping!
var arr = string.split(",");
var weeks = {};
for (var i = 0; i < arr.length; i++) {
var currentArr = arr[i].split("|");
var week = currentArr[0];
var issue = currentArr[1];
var priority = currentArr[2];
if (!(week in weeks))
weeks[week] = {1:[], 2:[], 3:[]};
// if the number of issues levels were unknown,
// you'd start with an empty object instead
// and create the arrays dynamically in a manner similar to the weeks
weeks[week][priority].push(issue);
}
return Object.keys(weeks).map(function(week) {
return [week, weeks[week][1], weeks[week][2], weeks[week][3]];
});
(to get the result ordered by week number, add a sort(function(a,b){return a-b}) before the .map() call)
In your situation I would recommand to put the values in the array first. In the second step I would sort the array using the sort method.
function getSortedArrayByString(myString) {
var arraySplittedString, i, tmpValueArray, tmpInnerArray, resultingArray;
arraySplittedString = myString.split(",");
resultingArray = [];
for(i = 0; i < arraySplittedString.length; i++){
// tmpArray has the format of [<week>, <IssuesPriority1>, <IssuesPriority2>]
tmpValueArray = arraySplittedString[i].split("|");
// Push it in the new array.
resultingArray.push(tmpValueArray);
}
// Sort array by weeks ascending.
resultingArray.sort( function (a, b) {
return a[0] - b[0];
});
return resultingArray;
}
Running fiddle.
If you also want to sort by the count of issues, you simply can customize the inner sort function.
With this solution all values are saved as strings. You can convert them by using the parseInt function.

Categories

Resources