I have two array.They looks like
var productId = [2,3,5];
var quantity = [10,13,15];
Now I want to merge these array in one array and store in local storage.New array looks like
var newArray = [2 =>'10',3=>'13',5=>'15'];
You can create object instead using Object.assign and map methods.
var productId = [2,3,5];
var quantity = [10,13,15];
var obj = Object.assign({}, ...productId.map((e, i) => ({[e]: quantity[i]})))
console.log(obj)
// localStorage.setItem('foo', JSON.stringify(obj))
// console.log(JSON.parse(localStorage.getItem('foo')))
Or you can use reduce method instead of map.
var productId = [2,3,5];
var quantity = [10,13,15];
var obj = productId.reduce((r, e, i) => (r[e]= quantity[i], r), {})
console.log(obj)
I can see that you want to merge two arrays with same length such that merged array will have keys from first array and values from second array. But unlike php, JavaScript doesn’t have concept of array with key and value pairs. What you can do is create a merged object with key value pair.You can achieve by creating a custom function which does that. So, the code for it would be something like:
let arrayA = ["name", "address", "phone"];
let arrayB = ["Niraj", "Kathmandu", "98423232223"];
function array_combine(a, b)
{
if(a.length != b.length) return false;
let combObj = {};
for (i = 0; i < a.length; i++)
{
combObj[a[i]] = b[i];
}
return combObj;
}
let combined_obj = array_combine(arrayA, arrayB);
console.log(combined_obj);
You can directly use reduce method of ES6 as well for the purpose.
let arrayA = ["name", "address", "phone"];
let arrayB = ["Niraj", "Kathmandu", "98423232223"];
let combined_obj =
arrayA.reduce((obj, k, i) => ({...obj, [k]: arrayB[i] }), {}));
If you now want to store the combined_array in local storage, you can do that, by first stringifying it and then store it.
let combined_obj = JSON.stringify(array_combine(arrayA, arrayB));
localStorage.setItem('combinedObj', combined_obj);
Related
I have an array of object as follows:
var arr=[ {"jan":2},{"jan":5},{"feb":3},{"feb":1}];
Their will be N number of objects with any combination keys jan & feb is just an example.
I need to find average of objects with similar keys so that resultant array looks like this :
var newArr=[{"jan":3.5},{"feb":2}];
Looking to achieve this without reduce method in JavaScript.
I tried to seperate out objects with similar keys so that ic an sum and average them and push in to a new aray. something like this :
arr.forEach(a=>{
console.log(Object.keys(a))
console.log(arr.filter(ar=>ar.hasOwnProperty(Object.keys(a)[0])))
})
But it creates multiple groups for same keys like this in console.
[ {"jan":2},{"jan":5} ]
[ {"jan":2},{"jan":5} ]
[ {"feb":3},{"feb":1} ]
[ {"feb":3},{"feb":1} ]
A code without using reduce . A bit length though but easy to understand
We are using two objects , one is to store the count of the keys and other is for storing the total of the keys.
result object has the average.
var arr=[ {"jan":2},{"jan":5},{"feb":3},{"feb":1}];
var count = {};
var total = {};
arr.forEach(obj => {
var key = Object.keys(obj)[0];
if(count.hasOwnProperty(key)){
count[key]=count[key]+1;
} else {
count[key]=1;
}
if(total.hasOwnProperty(key)){
total[key]=total[key]+obj[key];
} else {
total[key]=obj[key];
}
})
var result = {}
Object.keys(total).forEach(key => {
result[key] = total[key]/count[key];
})
console.log(result)
Similar to the answer above, but makes use of a map:
var arr=[ {"jan":2},{"jan":5},{"feb":3},{"feb":1}];
let map = new Map();
let keyCount = {};
arr.forEach(e => {
let key = Object.keys(e)[0];
let value = Object.values(e)[0];
if (map.get(key) !== undefined) {
map.set(key, map.get(key) + value);
keyCount[key] = keyCount[key] + 1;
} else {
map.set(key, value);
keyCount[key] = 1;
}
});
let newArr = [];
for (let e of map.entries()) {
let obj = {};
obj[e[0]] = e[1] / keyCount[e[0]];
newArr.push(obj);
}
console.log(newArr);
I have two arrays and need to fill the missing values with NA by comparing the levels present in other array. I used the arr.find to search but not sure how to proceed further.
Input:
const levels = [1,2,3,4]
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}]
Output:
out = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":2,"NAME1":"NA"},{"LEVEL":3,"NAME1":"TOM"},{"LEVEL":4,"NAME1":"NA"}]
Code:
let presentLevels = [];
for (let i = 1; i <= levels.length; i++) {
let check = arr.find(p => p['LEVEL'] === levels[i])
if (check) {
presentLevels.push(i)
}
}
console.log(presentLevels)
You can use map() the levels array. Find the object with LEVEL equal to the current element. If you find an object then just return that otherwise return a new object with LEVEL and NAME1 props
const levels = [1,2,3,4]
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}]
const res = levels.map(x => (arr.find(a => a.LEVEL === x) || {level: x, NAME1: "NA"}));
console.log(res)
Using Array.find() inside a loop might cause a performance issue if the arr is large enough. I would create a Map of existing levels by LEVEL, and then use the Map to get the existing levels.
Since you want the presentLevels array to be ordered by the number of the level, you'll need to iterate the levels array, and return a new array. You can do this easily with Array.map(). On each iteration take the current level from the existing Map, and if not found in existing return a new object with NA.
const levels = [1, 2, 3, 4]
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}]
const existingMap = new Map(arr.map(o => [o.LEVEL, o]))
const presentLevels = levels.map(LEVEL =>
existingMap.get(LEVEL) || { LEVEL, NAME1: 'NA' }
);
console.log(presentLevels)
You can make a loop with levels to get the items which arr doesn't have, then adding that items to arr
const levels = [1,2,3,4]
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}]
var items = levels.filter(level => !arr.find(item => item.LEVEL === level));
items.forEach(level => arr.push({LEVEL: level, NAME1: "NA"}));
console.log(arr.sort((a, b) => a.LEVEL - b.LEVEL));
You could first map the levels to the object array with all NA, and then iterate arr to replace those where necessary:
const levels = [1,2,3,4];
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}];
const result = levels.map(LEVEL => ({LEVEL, NAME1: "NA"}) );
for (let o of arr) result[o.LEVEL-1] = o;
console.log(result);
Although this executes two loops, they are not nested, and so this task is performed with linear time complexity (contrary to solutions that have a find call inside the loop).
maybe like this:
const levels = [1,2,3,4];
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}];
for(var key_l in levels){
var found_levels = false;
for(var key_ar in arr){
if(arr[key_ar].LEVEL == levels[key_l]){
found_levels = true;
}
}
if(!found_levels){
arr.push({"LEVEL":levels[key_l],"NAME1":"NA"});
}
}
/* for result sorting, if need... */
arr.sort(function(a, b){
return a.LEVEL > b.LEVEL;
});
console.log(arr);
I have to construct an array of objects. I can do it "long hand," but I'm hoping to find a way to iterate through some variables and check each at "push" them into the right spot in the array.
I have this:
//this is the starting array...I'm going to update these objects
operationTime = [
{"isActive":false,"timeFrom":null,"timeTill":null},//Monday which is operationTime[0]
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null}
];
//I get the below via an API call
var monHours = placeHours.mon_open_close;
var tueHours = placeHours.tue_open_close;
var wedHours = placeHours.wed_open_close;
var thuHours = placeHours.thu_open_close;
var friHours = placeHours.fri_open_close;
var satHours = placeHours.sat_open_close;
var sunHours = placeHours.sun_open_close;
var sunHours = placeHours.sun_open_close;
//here's where I'm stuck.
if (monHours.length>0){
var arr = monHours[0].split("-");
operationTime[0].isActive= true;
operationTime[0].timeFrom= arr[0];
operationTime[0].timeTill= arr[1];
}
else {
operationTime[0].isActive= false;
}
My if/else works perfectly in the above example using Monday, but I don't want to write this for seven days of the week making it unnecessarily complicated. How could I condense this into a single "function" that'll test each variable and push it into the array object in the correct position?
I guess you can put the keys in an array, and then use forEach loop through operationTime and update the object based on the index:
operationTime = [
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null}
];
// make an array of keys that has the same order of the operationTime
var keys = ['mon_open_close', 'tue_open_close', 'wed_open_close', 'thu_open_close', 'fri_open_close', 'sat_open_close', 'sun_open_close'];
var placeHours = {'mon_open_close': ['08:00-17:00'], 'tue_open_close':[], 'wed_open_close':[], 'thu_open_close':[], 'fri_open_close':[], 'sat_open_close':[], 'sun_open_close':['10:20-15:30']}
operationTime.forEach( (obj, index) => {
var dayHours = placeHours[keys[index]];
if(dayHours.length > 0) {
var arr = dayHours[0].split("-");
obj.isActive= true;
obj.timeFrom= arr[0];
obj.timeTill= arr[1];
}
})
console.log(operationTime);
You can try this way with foreach all days's hour,
$all_hours = [monHours, tueHours , wedHours , thuHours , friHours , satHours ,sunHours];
foreach($all_hours as $k=>$hours){
if ($hours.length>0){
$arr = $hours[k].split("-");
operationTime[$k].isActive= true;
operationTime[$k].timeFrom= $arr[0];
operationTime[$k].timeTill= $arr[1];
}
else {
operationTime[$k].isActive = false;
}
}
You can use Object.entries() to iterate properties and values of an object as an array, .map() to define and include index of iteration in block of for..of or other loop. The index is utilized to reference object at index of operationTime array
for (let
[key, prop, index]
of
Object.entries(placeHours)
.map(([key, prop], index) => [key, prop, index]))) {
if (prop.length > 0 ) {
let [arr] = prop.split("-");
operationTime[index].isActive = true;
operationTime[index].timeFrom = arr[0];
operationTime[index].timeTill = arr[1];
}
}
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"]
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);