I have two objects:
a = {A: 1, B: 2};
a = {C: 3, D: 4};
I need to put the property values of the objects in to one array. So, i'm doing this by iterate each of the objects, but what next, pushing it into one array returns two separated...
$.each(a, function(_key, _val) {
var arr = [];
arr.push(_val);
console.log(arr);
});
How to do this? Is it possible?
I need this: arr = [1, 2, 3, 4];
You are initializing the arr inside the each everytime. Try this:
var arr = [];
$.each(a, function(_key, _val) {
arr.push(_val);
console.log(arr);
});
Here is a fiddle:
https://jsfiddle.net/aarLgmtL/
var a = {A: 1, B: 2};
var b = {C: 3, D: 4};
function join(source, target) {
$.each(source, function(_key, _val) {
target.push(_val);
});
}
var arr = [];
join(a, arr);
join(b, arr);
$("#result").html(JSON.stringify(arr));
You could try using .concat as well. Here is an example from w3schools:
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
http://www.w3schools.com/jsref/jsref_concat_array.asp
Is this what you are looking for?
Don't initialize array in $.each function. It will assign new array every time $.each function call so it end up with last array element in arr variable.
a = {
A: 1,
B: 2
};
b = {
C: 3,
D: 4
};
var arr = [];
function pushToArray(a) {
$.each(a, function(_key, _val) {
arr.push(_val);
});
}
pushToArray(a);
pushToArray(b);
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Make sure that you don't define different object with same name else end up with last object assigned to that variable.
You can simply achieve this by using Object.assign
var a = {A: 1, B: 2};
var b = {C: 3, D: 4};
var copy = Object.assign(a, b);
var result =[];
for(var i in copy){
result.push(copy[i]);
}
console.log(result);
Thanks.
The approach outlined below first creates two separate arrays, one from a and one from b, and then concatenates them together (with a little help from the jQuery Array#map method.)
a = {A: 1, B: 2};
b = {C: 3, D: 4};
var arrayFromA = $.map(a, function(value, index) {
return [value];
});
var arrayFromB = $.map(b, function(value, index) {
return [value];
});
finalArray = arrayFromB.concat(arrayFromA);
Related
function select(arr, obj) {
var myKeys = Object.keys(obj);
var myValues = Object.values(obj);
var newObj = {};
for(var i=0; i<myKeys.length; i++) {
if(arr[i] === myKeys[i]) {
newObj[myKeys[i]] = myValues[i];
}
}
return newObj;
}
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }
/*
If keys are present in the given array, but are not in
the given object, it should ignore them.
It does not modify the passed in object.
*/
I'm having trouble adding an array as an object property. I created a new Object to store the values in, however it only stores the first instance of arr[i]. I'm confused at this point any help?
Do this instead
for(var i=0; i<arr.length; i++) {
if(myKeys[arr[i]] !== undefined) {
newObj[arr[i]] = myValues[i];
}
}
Your code works only if the index of matching keys is exactly the same.
The problem in your code is that it assumes that the ith value in the array must correspond to the ith key of the object, but that order is not guaranteed.
Here is a functional programming style solution, that uses Obect.fromEntries to construct the returned object:
const select = (arr, obj) =>
Object.fromEntries(arr.filter(key => key in obj).map(key => [key, obj[key]]));
var arr = ['a', 'c', 'e'];
var obj = {a: 1,b: 2,c: 3,d: 4};
var output = select(arr, obj);
console.log(output);
I'd use the relatively recently added Object.fromEntries to create an object directly from a map of a filtered set of keys from your object.
function select (arr, obj) {
// get the keys from obj and filter to those present in arr
var keys = Object.keys(obj).filter(key => arr.includes(key));
// create an array of arrays where each inner array has a key and value
var entries = keys.map(key => [key, obj[key]]);
// call fromEntries with that new array.
return Object.fromEntries(entries);
}
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }
/*
If keys are present in the given array, but are not in
the given object, it should ignore them.
It does not modify the passed in object.
*/
I have a simple question. I have two arrays A and B, I want to return array of object with mixing the two arrays.
For example:
let a = [ 1, 2 ]
let b = [ 3, 4 ]
Expected result:
const C = [
{
a: 1,
b: 3
},
{
a: 2,
b: 4
}
]
How can I do this?
I tried to forloop A then B and assign everytime but it didn't work.
You can use array map method on one of the array and use index to retrieve the element from the second array
let a = [1, 2]
let b = [3, 4];
let c = a.map((item, index) => {
return {
a: item,
b: b[index]
}
});
console.log(c)
Something like this should work:
let a = [1, 2];
let b = [3, 4];
// From #brk. This transforms each element of a to an object containing a's value and b's value
let c = a.map((item, index) => {
a: item,
b: b[index]
});
// Another way. Iterates through each element
for (let i = 0; i < a.length; i++) {
c[i].a = a[i];
c[i].b = b[i];
}
// Yet another. A combination of the first two.
for (let [index, item] of Object.entries(a)) {
c[index] = {
a: item,
b: b[index]
};
}
There's certainly a more elegant solution, but it evades me at the moment
I have two sets of arrays:
var a = [1, 2, {a: 1, b:2}, 3];
var b = [1, {a: 1, b: 2}, 3};
If array a has ALL (EXACT) the properties and values of array b (including objects) then it will increment count by 1. Otherwise, if array a has only some properties and some values doesn't match, it will just exit and do nothing.
As an example:
var a = [1, 2, {a: 1, b:2}, 3];
var b = [1, {a: 1, b: 2}, 3};
// return true / count++
var a = [1, 2, 3, {a: 1, b: 4}];
var b = [1, 2, {a: 1, b: 6}, 3];
return false / no count
Here's my program first:
for(var i = 0; i < mainArr[i]; i++){
if(arr.includes(mainArr[i])){
count++;
}
if(typeof(mainArr[i]) === 'object' && typeof(arr[i]) === 'object'){
for(var mainArrProp in mainArr[i]){
for(var arrProp in arr[i]){
if(arr[i].hasOwnProperty(mainArrProp) && arr[i][arrProp] === mainArr[i][mainArrProp]){
count++;
}
}
}
}
}
Any way to fix this?
If you can use es6, you can leverage some of the new methods to make a (relatively) short function to do this. Specifically we would make use of the array includes, every, and some methods to check for shallow object equality:
function getIncrementValue(set, subset) {
for (let item of subset) {
if (typeof item === "object") {
// Special case if looking at an object. I am assuming object is always shallow.
if (!set.some(otherItem => typeof otherItem === "object" && Object.keys(otherItem).length === Object.keys(item).length && Object.keys(otherItem).every(key => (key in item) && item[key] === otherItem[key]))) return 0;
} else {
if (!set.includes(item)) return 0;
}
}
return 1;
}
// So for your arrays:
var a1 = [1, 2, {a: 1, b:2}, 3];
var b1 = [1, {a: 1, b: 2}, 3];
// return true / count++
var a2 = [1, 2, 3, {a: 1, b: 4}];
var b2 = [1, 2, {a: 1, b: 6}, 3];
// return false / no count
console.log(getIncrementValue(a1, b1)) // returns 1;
console.log(getIncrementValue(a2, b2)) // returns 0;
This is pretty straightforward except for that one long line that checks for object equality. But all that says is:
If there is not some element of set that:
is an object, and
the element and our current item have the same number of keys, and
every key of that element is a key of our current item, and
the values for each key are the same
Then return 1.
You're following totally wrong way, you don't need to work with regular count++ in your case, you should better decrease by one and return, if any value from arrayA doesn't exist in arrayB. I rewrote the method with explanation of each row, I think, it should be clear what's going on. I also noticed, that you write in ES5, but you also use includes(), it's a ES6 feature, good to know. I have left includes() in my implementation too. My method returns 1 if all values from the first array exists in the second, and returns 0 if not. Here it is:
function test(a, b) {
var count = 1,
/* "aValues" will contain both single numbers and object values from "a" array */
aValues = createHomogeneousArray(a),
/* "bValues" will contain both single numbers and object values from "b" array */
bValues = createHomogeneousArray(b);
/* Check does each value of "aValues" exists in "bValues" array, if not - return "count--" (will be equal to "0") */
aValues.forEach(function(item) {
if (!bValues.includes(item)) {
return count--
}
});
/* If nothing was returned yet, return count (is equal to "1") */
return count;
}
function createHomogeneousArray(arr) {
var finalArr = [];
/* Iterate through array */
arr.forEach(function(item) {
/* Check is object */
if (typeof item === 'object') {
/* If object - get all values of this object as array */
var arrOfObjValues = Object.values(item);
/* Iterate through this array with object values */
arrOfObjValues.forEach(function(value) {
/* Push each value of above array to the "finalArr" array, which contains ALL values of the array, passed to this function */
finalArr.push(value);
});
/* Check is number */
} else if (typeof item === 'number') {
/* Push all regular numbers to final array */
finalArr.push(item);
}
});
/* Return "finalArr" array */
return finalArr;
}
console.log(test(
[1, 2, {a: 1, b:2}, 3],
[1, {a: 1, b: 2}, 3]
))
console.log(test(
[1, 2, 3, {a: 1, b: 4}],
[1, 2, {a: 1, b: 6}, 3]
))
Don't be scared of the size of the code, it's much smaller without comments:
function test(a, b) {
var count = 1,
aValues = createHomogeneousArray(a),
bValues = createHomogeneousArray(b);
aValues.forEach(function(item) {
if (!bValues.includes(item)) {
return count--
}
});
return count;
}
function createHomogeneousArray(arr) {
var finalArr = [];
arr.forEach(function(item) {
if (typeof item === 'object') {
var arrOfObjValues = Object.values(item);
arrOfObjValues.forEach(function(value) {
finalArr.push(value);
});
} else if (typeof item === 'number') {
finalArr.push(item);
}
});
return finalArr;
}
console.log(test(
[1, 2, {a: 1, b:2}, 3],
[1, {a: 1, b: 2}, 3]
))
console.log(test(
[1, 2, 3, {a: 1, b: 4}],
[1, 2, {a: 1, b: 6}, 3]
))
I would like to sort an array into and object with key value pairs.
So if I had an array like this [1,2,3,2,4,1,5,1,6] it should spit out something like this. I was trying to use lodash for it!
{
1: [1, 1, 1],
2: [2, 2],
3: [3],
4: [4],
5: [5],
6: [6]
}
You can use reduce() and return object.
var ar = [1, 2, 3, 2, 4, 1, 5, 1, 6];
var result = ar.reduce(function(o, e) {
o[e] = (o[e] || []).concat(e);
return o;
}, {});
console.log(result)
Some basic iteration would do that, where you either set an array, or push to an existing array
var arr = [1,2,3,2,4,1,5,1,6];
var obj = {};
arr.forEach( (x) => x in obj ? obj[x].push(x) : obj[x] = [x]);
document.body.innerHTML = '<pre>'+ JSON.stringify(obj, 0, 4) +'</pre>'
const arr = [1,2,3,2,4,1,5,1,6];
const r = {};
arr.forEach(e=>r[e]?r[e].push(e):r[e]=[e]);
console.log(r);
Here is a very simple pure JavaScript version to achieve this (https://jsfiddle.net/azkuodyc/)
var array = [1,2,3,2,4,1,5,1,6];
var newArrayObject = {};
for (key in array) {
var value = array[key];
if (typeof newArrayObject[key] == 'undefined') {
newArrayObject[key] = [];
}
newArrayObject[key].push(value);
}
One other way of doing this is;
var arr = [1,2,3,2,4,1,5,1,6],
obj = arr.reduce((p,c) => (p[c] = p[c] ? p[c].concat(c) : [c],p),{});
console.log(obj);
var arr = [1,2,3,2,4,1,5,1,6];
var res = _(arr).countBy().mapValues((value, key) => {
return _.times(value, _.constant(parseInt(key)));
}).value();
console.log(res);
https://jsfiddle.net/7bppaxx5/
I have a object like that one:
Object {a: 1, b: 2, undefined: 1}
How can I quickly pull the largest value identifier (here: b) from it? I tried converting it to array and then sorting, but it didn't work out, since it got sorted alphabetically (and it seems like a overkill to juggle data back and forth just for getting one value out of three).
For example:
var obj = {a: 1, b: 2, undefined: 1};
Object.keys(obj).reduce(function(a, b){ return obj[a] > obj[b] ? a : b });
In ES6:
var obj = {a: 1, b: 2, undefined: 1};
Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b);
Using Underscore or Lo-Dash:
var maxKey = _.max(Object.keys(obj), function (o) { return obj[o]; });
With ES6 Arrow Functions:
var maxKey = _.max(Object.keys(obj), o => obj[o]);
jsFiddle demo
Here is a suggestion in case you have many equal values and not only one maximum:
const getMax = object => {
return Object.keys(object).filter(x => {
return object[x] == Math.max.apply(null,
Object.values(object));
});
};
This returns an array, with the keys for all of them with the maximum value, in case there are some that have equal values.
For example: if
const obj = {apples: 1, bananas: 1, pears: 1 }
//This will return ['apples', 'bananas', 'pears']
If on the other hand there is a maximum:
const obj = {apples: 1, bananas: 2, pears: 1 }; //This will return ['bananas']
---> To get the string out of the array: ['bananas'][0] //returns 'bananas'`
Supposing you've an Object like this:
var obj = {a: 1, b: 2, undefined: 1}
You can do this
var max = Math.max.apply(null,Object.keys(obj).map(function(x){ return obj[x] }));
console.log(Object.keys(obj).filter(function(x){ return obj[x] == max; })[0]);
{a: 1, b: 2, undefined: 1}
The best work around I've seen is this
const chars = {a: 1, b: 2, undefined: 1}
//set maximum value to 0 and maxKey to an empty string
let max = 0;
let maxKey = "";
for(let char in chars){
if(chars[char]> max){
max = chars[char];
maxKey= char
}
}
console.log(maxKey)
Very basic method. might be slow to process
var v = {a: 1, b: 2, undefined: 1};
function geth(o){
var vals = [];
for(var i in o){
vals.push(o[i]);
}
var max = Math.max.apply(null, vals);
for(var i in o){
if(o[i] == max){
return i;
}
}
}
console.log(geth(v));
Combination of some ideas from other answers. This will get all the keys with the highest value, but using the spread operator to get the maximum value and then filter array method:
const getMax = object => {
let max = Math.max(...Object.values(object))
return Object.keys(object).filter(key => object[key]==max)
}
let obj = {a: 12, b: 11, c: 12};
getMax(obj)
let data = {a:1,b:2,undefined:3}
let maxValue = Object.entries(data).sort((x,y)=>y[1]-x[1])[0]
note: this is a very expensive process and would block the event loop if used with objects of large sizes(>=1000000). with large array slice the entries and call the above method recurrently using setTimeout.
If you need to return an array from an object with the keys for all duplicate properties with the (same or equal) highest value, try this:
const getMax = Object.keys(object)
.filter(x => {
return object[x] == Math.max.apply(null,
Object.values(object));
})
var object = { orange: 3, blue: 3, green: 1}
console.log(getMax) // ['orange', 'blue']