Javascript multidimensional array key - val [duplicate] - javascript

This question already has answers here:
Zip arrays in JavaScript?
(5 answers)
Closed 5 years ago.
In my javascript function i have two single array like this:
var row = ["var1","var2","var3"];
var col = ["res1","res2","res3"];
i would create a multidimensional array like:
[["var1","res1"],["var2","res2"],["var3","res3"]]
i tried:
new Array(m).fill(new Array(n).fill(0));
or solution like:
var dict = [[]];
for (i = 0; i < descendents.length; i++) {
e = descendents[i];
dict[i] = dict[i][e.id]
dict[i] = dict[i][e.value]
}
but the result is not correct for me. i don't know how achieve this
Thanks in advance

Use Array#map to generate a new array based on existing.
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];
// iterate and generate new array based on row array element
// and fetch element from col using the same index
var res = row.map((v, i) => [v, col[i]]);
console.log(res)
Or with Array.from with a map function.
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];
var res = Array.from({ length: row.length }, (_, i) => [row[i], col[i]]);
console.log(res)

Related

How to push data without hardcoding the name [duplicate]

This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 4 months ago.
I want to build an JSON with name and value like name:"john".
This is my code:
var allFields = [];
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length;i++){
name = inputs[i].name;
item = inputs[i].value;
allFields.push({name: item});
}
var alleFelder = JSON.stringify(allFields);
alert(alleFelder);
My problem is that "name" gets hardcorded into the JSON.
So instead of...:
name:"john",
lastname:"brooks",
birthdate:"1.1.1999"
...im getting:
name:"john",
name:"brooks",
name:"1.1.1999"
You can use this simple function to add new keys with values to your object
const myObj = {}
function addKeyVal(obj, k, v){
obj[k] = v;
}
const keys = ["name", "bday"];
const values = ["Jhon", "1-1-2020"];
for(let i = 0; i < keys.length; i++)addKeyVal(myObj, keys[i], values[i])
console.log(myObj)

how to join two arrays in js to get an new array with both its values [duplicate]

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]]

how to sort and get last value and index in javascript [duplicate]

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])

find duplicates in two arrays [duplicate]

This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 7 years ago.
I have two arrays like this:
var x = ['1','2','6'];
var y = ['4', '5','6'];
How do I find duplicates in two arrays in pure JavaScript and I would like to avoid using a loop?
Output - duplicates: 6
Try something like this:
var x = ['1','2','6'];
var y = ['4', '5','6'];
var overlap = x.filter(function(v,i,a){
return y.indexOf(v) > -1;
});
console.log(overlap); // ['6']
Does this work for your purpose?
MDN docs for filter
Try this
var x = ['1','2','6'];
var y = ['4', '5','6'];
var duplicate = [];
for (var i=0; i<y.length; i++) {
var index = x.indexOf(y[i]);
if (index > -1) {
duplicate.push(x[index]);
}
}
Output: ["6"]

Create child objects from parent with same property values [duplicate]

This question already has answers here:
How to put items into grouped arrays where grouped by a particular key
(3 answers)
Closed 9 years ago.
I have a parent object. I want to create child objects from the parent with the same key value pair.
e.g.
parentJSON = {[name:"a1",address:"b1",comp:"c1"],
[name:"a2",address:"b2",comp:"c1"],
[name:"a3",address:"b3",comp:"c2"],
[name:"a4",address:"b4",comp:"c2"],
[name:"a5",address:"b5",comp:"c2"],
[name:"a6",address:"b6",comp:"c3"]}
Now I want to create child objects having same "comp" value.
e.g.
childJSON1 = {[name:"a1",address:"b1",comp:"c1"],
[name:"a2",address:"b2",comp:"c1"]}
childJSON2 = {[name:"a3",address:"b3",comp:"c2"],
[name:"a4",address:"b4",comp:"c2"],
[name:"a5",address:"b5",comp:"c2"]}
childJSON3 = {[name:"a6",address:"b6",comp:"c3"]}
This is what I tried to make it little bit (it will change the parent object with a key indicating number of repetition):
parentJSON = [1,2,3,3,4,4,4,5];
var i=0, x, count, item;
while(i < parentJSON.length) {
count = 1;
item = parentJSON[i];
x = i+1;
while(x < parentJSON.length &&
(x = parentJSON.indexOf(item, x)) != -1) {
count += 1;
parentJSON.splice(x,1);
}
parentJSON[i] = new Array(parentJSON[i],count);
++i;
}
console.log(parentJSON);`
first of all your json is in the incorrect format, it should look like this
[{name:"a1",address:"b1",comp:"c1"},
{name:"a2",address:"b2",comp:"c1"},
{name:"a3",address:"b3",comp:"c2"},
{name:"a4",address:"b4",comp:"c2"},
{name:"a5",address:"b5",comp:"c2"},
{name:"a6",address:"b6",comp:"c3"}]
An array of objects.
My attempt, also very readable.
var result = {};
$.each(parentJSON, function (i, item) {
if(!result[item.comp]) {
result[item.comp] = [];
}
(result[item.comp]).push(item);
});
alert(JSON.stringify(result))
JsFiddle
First of all your json is actually invalid. You may have an array of objects, but not object which contains an array like that. Also your arrays looks more like objects, because the syntax with the dots is used for objects. Here is how I guess should look like:
var parentJSON = [
[{name:"a1",address:"b1",comp:"c1"}],
[{name:"a2",address:"b2",comp:"c1"}],
[{name:"a3",address:"b3",comp:"c2"}],
[{name:"a4",address:"b4",comp:"c2"}],
[{name:"a5",address:"b5",comp:"c2"}],
[{name:"a6",address:"b6",comp:"c3"}]
];
var child1 = parentJSON.slice(0, 2);
var child2 = parentJSON.slice(2, 5);
And you may use the .slice method to get specific elements of the array.
So..you need to clone objects?
maybe tou can try sth like this:
var sergi= {
name: "sergi",
age: 33
};
var bill = (JSON.parse(JSON.stringify(sergi)));
bill.name = "Bill";
console.log(sergi);
console.log(bill);
parentJSON = function(){
return [
{name:"a1",address:"b1",comp:"c1"},
{name:"a2",address:"b2",comp:"c1"},
{name:"a3",address:"b3",comp:"c2"},
{name:"a4",address:"b4",comp:"c2"},
{name:"a5",address:"b5",comp:"c2"},
{name:"a6",address:"b6",comp:"c3"}
];
}
childJSON1 = new parentJSON().slice(0,2);
childJSON2 = new parentJSON().slice(2,5);
childJSON3 = new parentJSON().slice(5,6);
Try this:
DEMO
var data = [
[{name:"a1",address:"b1",comp:"c1"}],
[{name:"a2",address:"b2",comp:"c1"}],
[{name:"a3",address:"b3",comp:"c2"}],
[{name:"a4",address:"b4",comp:"c2"}],
[{name:"a5",address:"b5",comp:"c2"}],
[{name:"a6",address:"b6",comp:"c3"}]
];
var groups = {};
$.each(data, function(i, item) {
var comp = item.comp;
delete item.comp;
if(groups[comp]) {
groups[comp].push(item);
} else {
groups[comp] = [item];
}
});
var result = $.map(data, function(group, key) {
var obj = {};
obj[key] = group;
return obj;
});
alert(JSON.stringify(groups))

Categories