This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 7 months ago.
consider this two arrays array y and array x i need to concatenates them but not after each other but be organised as in the form of array k
the concatenate method just output them after each other
let x=['name','age','id'];
let y=['kyle',50,5050];
let k= x.concat(y);
the output i get is
k=['name','age','id','kyle',50,5050]
so how to merge them to get this output array
let k=['name':'kyle','age':50,'id':5050]
This is possible, but not as an array. You need an object.
const x = ['name', 'age', 'id'];
const y = ['kyle', 50, '5050'];
const k = {};
x.forEach((element, index) => {
k[element] = y[index];
});
console.log(k);
In fact, the javascript array doesn't look like this. We can have an array of objects or array of arrays
let keys=['name','age','id'];
let values=['kyle',50,5050];
var array = keys.map((el, i) => {
return {[keys[i]]:values[i]}
}); // as array of objects
var array = keys.map((el, i) => {
return [keys[i], values[i]];
}); // as array of arrays
of if you want a single object you can use
let obj = {};
keys.forEach((element, index) => {
obj[element] = values[index];
});
This should work for you
Note: k is not an array, it's an object read about JavaScript object here
let x = ['name', 'age', 'id'];
let y = ['kyle', 50, 5050];
let k = {};
x.forEach((item, index) => {
k[item] = y[index];
});
console.log(k);
Simply with map:
let x = ['name', 'age', 'id'];
let y = ['kyle', 50, 5050];
k= x.map((prop, i) => [prop, y[i]]);
console.log(k);// [["name","kyle"],["age",50],["id",5050]]
This question already has answers here:
get key of max value in dictionary nodejs
(2 answers)
Getting key with the highest value from object
(9 answers)
Closed 2 years ago.
i create a let in JavaScript below format
let map={'431':232,'432':123,'433':120}
i want to order the map into following format. order by value.
map={'433':120,'432':123,'431':232}
at last i need to store index and value as numbers.
int1=431 // index as number
int2=232 // values as number
Convert the object to an entries array
Sort it by key (entry[0])
Grab the last entry by index or via Array.prototype.pop()
let map = {'431':232,'432':123,'433':120}
const sorted = Object.entries(map).sort(([ key1 ], [ key2 ]) =>
key2 - key1)
const [ int1, int2 ] = sorted[sorted.length - 1]
console.info(int1, int2)
Use Object.entries, sort them and take the first element (using destructure)
let map = { '431': 232, '432': 123, '433': 120 };
const [[key, value]] = Object.entries(map).sort(([a], [b]) => +a - +b);
console.log(key, value);
it creates your goal object and what you want you can find.
let map={'431':232,'432':123,'433':120}
var keys = [];
var values = [];
for(var k in map) keys.push(parseInt(k));
for(var v in map) values.push(map[v]);
values = values.sort().reverse();
let finalObj=[];
for(i=0;i<keys.length;i++){
let obj = {};
obj[keys[i]] = values[i];
finalObj.push(obj)
}
console.log(finalObj[finalObj.length-1])
This question already has answers here:
Sorting object property by values
(44 answers)
Closed 4 years ago.
I have the map posted below in the code section. what i want to achieve is, to sort the map according to the values ascendingly. so that, after sorting it,
i should the map sorted as shown in last section.
please let me know how can i achieve that.
code:
const map = {};
map['test.truck'] = 10;
map['test.domain'] = -20;
map['test.institute'] = 0;
map['test.vehicle'] = 40;
map['test.lan'] = 1;
map['test.wifi'] = 9;
after sorting:
map['test.domain'] = -20;
map['test.institute'] = 0;
map['test.lan'] = 1;
map['test.wifi'] = 9;
map['test.truck'] = 10;
map['test.vehicle'] = 40;
You can do:
const map = {};
map['test.truck'] = 10;
map['test.domain'] = -20;
map['test.institute'] = 0;
map['test.vehicle'] = 40;
map['test.lan'] = 1;
map['test.wifi'] = 9;
const mapSorted = Object
.keys(map)
.sort((a, b) => map[a] - map[b])
.reduce((a, c) => (a[c] = map[c], a), {});
console.log(mapSorted);
First, an important distinction: what you're using is an object, not a map. JavaScript has a separate Map class.
In any case, what you're asking for is not possible. Map entries do not have an internal order; it is entirely up to the JavaScript implementation to decide what order it returns them in when you iterate over them.
What you trying to do is sort object by property values.
Example:
const list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
const listSorted = Object.keys(list)
.sort((a, b) => list[a]-list[b])
.reduce((obj, key) => ({
...obj,
[key]: list[key]
}), {})
You should use these library.
https://www.npmjs.com/package/treemap-js
You'd have to convert to an array first and sort then:
function sortProperties(obj)
{
// convert object into array
var sortable=[];
for(var key in obj)
if(obj.hasOwnProperty(key))
sortable.push([key, obj[key]]); // each item is an array in format [key, value]
// sort items by value
sortable.sort(function(a, b)
{
var x=a[1].toLowerCase(),
y=b[1].toLowerCase();
return x<y ? -1 : x>y ? 1 : 0;
});
return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}
Case: We have 'n' number of arrays stored in an array (Array of Arrays). Now that each child array in this parent array can have elements that may or may not be present in other child arrays. Output - I need to create an array which has the all the elements present in all the child arrays excluding the duplicates.
I do not want to concatenate all the arrays into a single array and use unique method to filter out. I need to create unique array then and there during iteration.
Ex:
var a[] = [1,2,3,4,5];
var b[] = [1,2,7,8];
var c[] = [1,2,3,4,5,6,7,8];
var d[] = [9,10,11,12];
var arr[] = [a,b,c,d]
Output must be [1,2,3,4,5,6,7,8,9,10,11,12]
P.S: I can concat the arrays and use jquery unique function to resolve this, but i need a solution in javascript alone. Thanks
You can use array#reduce to flatten your array and then use Set to get distinct values and use array#from to get back array from Set.
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var arr = [a,b,c,d]
var result = Array.from(new Set(arr.reduce((r,a) => r.concat(a))));
console.log(result);
Try using .filter when adding each array to the final one, filtering out the duplicates:
a.filter(function(item) {
return !finalArray.contains(item));
});
Answer using Sets:
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var concat = a.concat(b).concat(c).concat(d);
var union = new Set(concat);
//console.log(union);
ES6 Answer:
let a = new Set([1,2,3,4,5]);
let b = new Set([1,2,7,8]);
let c = new Set([1,2,3,4,5,6,7,8]);
let d = new Set([9,10,11,12]);
let arr = new Set([...a,...b,...c,...d]);
//Result in arr.
Whats going on???
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set:
The Set object lets you store unique values of any type, whether
primitive values or object references.
So when we initialise Sets passing arrays to the constructor we basically ensure that there are no duplicate values.
Then in the last line, we concat all the Sets we initialised prior into a final set.
The ... notation converts the Set into an array, and when we pass the 4 arrays to the constructor of the Set they get concatenated and a Set of their unique values is created.
Here is a functional alternative written in ES5.
var flatten = function(list) {
return list.reduce(function(acc, next) {
return acc.concat(Array.isArray(next) ? flatten(next) : next);
}, []);
};
var unique = function(list) {
return list.filter(function(element, index) {
return list.indexOf(element) === index;
})
}
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var arr = [a,b,c,d];
var result = unique(flatten(arr));
console.log(result);
If you support ES6, arrow function can make that code even shorter.
Here is a solution that uses a plain object for resolving duplicates, and only uses basic ES3 JavaScript. Runs in IE 5.5 and higher, and with O(n) time complexity.
function uniques(arr) {
var obj = {}, result = [];
for (var i = 0; i < arr.length; i++) {
obj[arr[i]] = true;
}
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) result.push(+prop);
}
return result;
}
// Example use
var a = [1,2,3,4,5],
b = [1,2,7,8],
c = [1,2,3,4,5,6,7,8],
d = [9,10,11,12];
var result = uniques(a.concat(b, c, d));
console.log('Result: ' + result);
As an object can only have a unique set of properties (no duplicates), the use of all array values as properties in an object will give you an object with a property for each unique value. This happens in the first loop. NB: the value given to those properties is not relevant; I have used true.
Then the result is just the conversion of those properties back to array values. This happens in the second loop.
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var result = a.concat(b,c,d);
function remvDup(result){
var tmp = [];
for(var i = 0; i < result.length; i++){
if(tmp.indexOf(result[i]) == -1){
tmp.push(result[i]);
}
}
return tmp;
}
console.log(remvDup(result));
Becuase the OP mentioned that he cannot use 'Set' as it is not supported on the targeted browsers, I would recommand using the 'union' function from the lodash library.
See union's documentation here