Create an a multi diemensional array from different variables in Javascript - javascript

How do i create a multi-dimensional array from different javascript variables ?
For example, i have these three variables
var pdate = "|2019-12-26|2019-12-26|2019-12-26"
var products_id = "3354|5009|61927"
var products_category = "ENERGETICS|CASIO|SEIKO"
And i would like to transform them into this
var products_list = []
[0] = {pdate:"2019-12-26",products_id:"3354",products_category:"ENERGETICS"}
[1] = {pdate":"2019-12-26",products_id:"5009",products_category:"CASIO"}
[2] = {pdate:"2019-12-26",products_id:"61927",products_category:"SEIKO"}
Any ideas ?
Thanks

You can use the function split to separate the datas:
var pdate = "2019-12-26|2019-12-26|2019-12-26";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
var arrayPdate = getData(pdate);
var arrayProducts_id = getData(products_id);
var arrayProducts_category = getData(products_category);
var result = []
for (let i = 0; i < arrayPdate.length; i++) {
let jsonObject = {
pdate: arrayPdate[i],
products_id: arrayProducts_id[i],
products_category: arrayProducts_category[i]
}
result.push(jsonObject)
}
console.log(result);
function getData(c) {
return c.split("|")
}

You need use .split function on your string and then use loop with array index for others.
var pdate = "2019-12-26|2019-12-26|2019-12-26";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
pdate = pdate.split('|');
products_id = products_id.split('|');
products_category = products_category.split('|');
let arr = [];
for(let i=0; i<pdate.length; i++) {
arr.push({
pdate: pdate[i],
products_id: products_id[i],
products_category: products_category[i]
});
}
console.log(arr);

Related

How create two dimensional (2D) string array dynamic in JavaScript

If the word is ABC
A[0][0]="AA" A[0][1]="AB" A[0][2]="AC"
A[1][0]="BA" A[1][1]="BB" A[1][2]="BC"
A[2][0]="CA" A[2][1]="CB" A[2][2]="CC"
using for, string or array method.
const a = [..."ABC"];
console.log(
a.map(l => a.map(c => l + c))
);
An odd request. Is this what you are looking for?
const word = "ABC";
const letters = word.split("");
const array = [];
letters.forEach((letter1,index1) => {
letters.forEach((letter2,index2) => {
if (!array[index1]) {
array[index1] = [];
}
array[index1][index2] = letter1+letter2;
});
});
console.log(array);
UPDATE:
Another version using older Javascript. Also, check out Asaf's solution using a more functional approach below, is very elegant.
var word = "ABC";
var letters = word.split("");
var array = [];
for(var index1 = 0;index1!==letters.length;index1++) {
for(var index2 = 0;index2!==letters.length;index2++) {
if (!array[index1]) {
array[index1] = [];
}
array[index1][index2] = letters[index1]+letters[index2];
}
}
console.log(array);

Combine Array(s) into single object in JavaScript

Currently I have 3 arrays:
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
I would like to merge all the array into one object instead and I tried using for loop but got an error instead:
var finalObj = {};
for (var y = 0; y < dateArray.length; y++) {
finalObj[y].id = idArray[y];
finalObj[y].date = dateArrayArrange[y];
finalObj[y].content = contentArray[y];
}
The end result I want to achieve:
finalObj = [{id:13, date:20181920, content:"content1"},
{id:24, date:20181120, content:"content2"},
{id:35, date:20172505, content:"content3"}];
finalObj is an object you need to push the value in an array.Beside you can also use array map method which will return an array so there is no need to separately push the values to an array.
Use map method on any of the arrays and use the index to get the corresponding values from other array
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
let m = idArray.map(function(item, index) {
// here the map method will push the object to an
// array and will return that array
return {
id: item,
date: dateArray[index],
content: contentArray[index]
}
})
console.log(m)
Your finalObj is an array of objects, so you must initialise it as an array, like this :
var finalObj = [];
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
for (var y = 0; y < dateArray.length; y++) {
finalObj.push(
{ id: idArray[y], date: dateArray[y], content : contentArray[y] }
)
}
for the "pushing to final array" part, your code inside the loop may work if you add an extra finalObj[y] = {} to initialise it and so you have :
for (var y = 0; y < dateArray.length; y++) {
finalObj[y] = {}
finalObj[y].id = idArray[y];
finalObj[y].date = dateArray[y];
finalObj[y].content = contentArray[y];
}
an it works but
finalObj.push(
{ id: idArray[y], date: dateArray[y], content : contentArray[y] }
)
is shorter and still readable i think :)
let newObjArray = idArray.map((value, index) => {
return {
id: value,
date: dateArray[index],
content:contentArray[index]
}
});
console.log(newObjArray);
Well, I'm assuming you want an Array Of Objects which has the same length with the idArrays and others.
Here's some code for that:
var finalObjArray = [];
for (var y = 0; y < dateArray.length; y++) {
finalObjArray.push({
id: idArray[y],
date: dateArrayArrange[y],
content: contentArray[y]
});
}
Basically you are adding objects to that array. Hope it helps :)
There isn’t a record of finalObj[y] when you set properties, so it return undefined instead.
To fix your problem, create a object with properties then push it to your array.
You can do it like this:
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
var final = [];
for (let y = 0; y < idArray.length; y++) {
let tmp = {};
tmp.id = idArray[y];
tmp.date = dateArray[y];
tmp.content = contentArray[y];
final.push(tmp);
}
console.log(final)
Note: dateArrayArrange does not even exist, I think you mean just dateArray
You need to create objects and add them to the array. This code should work.
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
var finalObj = [];
for (var y = 0; y < dateArray.length; y++) {
object = {};
object.id = idArray[y];
object.date = dateArray[y];
object.content = contentArray[y];
finalObj[y] = object;
}
You could collect all key value pairs (for an arbitrary count) in an object and reduce the object while mapping the values.
var id = [13, 24, 35],
date = [20181920, 20181120, 20172505],
content = ["content1", "content2", "content3"],
result = Object
.entries({ id, date, content })
.reduce((r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
by using maps we can write a function which we can extend to any number of arrays and so on. the below function takes a minimum of three distinct fields.
function joinArrays(id, date, content,...array){
const Arr = [...array];
const newArr = new Array(Arr.length)
for(let i=0; i<newArr.length;i++){
newArr[i] ={}
}
Arr.map((rowArr,index)=>{
rowArr.map((i,k)=>
{
key = arguments[index];
let obj = {};
obj[key] = i;
newArr[k]=Object.assign(newArr[k],obj)}
)
}
)
console.log(newArr);
return newArr;
}
target = joinArrays('id', 'date', 'content',idArray,dateArray,contentArray);

seprate values from a string

I have 2 string like this
var a= '12,13,14,15,16';
var b='p,q,q,p,q';
I just need like this 12,15 represents p
and 13,14,16 represents q
How can I do this in Jquery/javascript.
var a = '12,13,14,15,16';
var b = 'p,q,q,p,q';
var as = a.split(",");
var bs = b.split(",");
if(as.length == bs.length)
{
var map = {};
for(var i = 0; i < as.length; ++i)
{
var asv = as[i];
var bsv = bs[i];
map[asv] = bsv;
}
console.log(map['13']); //q
}
or:
var a = '12,13,14,15,16';
var b = 'p,q,q,p,q';
var as = a.split(",");
var bs = b.split(",");
if(as.length == bs.length)
{
var map = {};
as.map(function(asv,idx){
return {asv:asv, bsv:bs[idx]};
})
.forEach(function(x){
map[x.asv] = x.bsv;
});
console.log(map['13']); //q
}
In answer to your comment, perhaps something like this would be better:
var a = '12,13,14,15,16';
var b = 'p,q,q,p,q';
var as = a.split(",");
var bs = b.split(",");
if(as.length == bs.length)
{
var map = {};
as.map(function(asv,idx){
return {asv:asv,bsv:bs[idx]};
})
.forEach(function(x){
if(!map[x.bsv])
{
map[x.bsv]=[];
}
map[x.bsv].push(x.asv);
});
console.log(map['q']); //["13", "14", "16"]
console.log(map['q'].join(",")); //"13,14,16"
}
Simple as this:
var a= '12,13,14,15,16';
var b='p,q,q,p,q';
var pValues=[], qValues=[]; //where to store the results
b.split(',').forEach(function(value, index){ //split the values from the b var
var aa=a.split(','); //split the values from the a var
if(value=='p') pValues.push(aa[index]);
if(value=='q') qValues.push(aa[index]);
});
console.log("pValues: "+pValues);
console.log("qValues: "+qValues);
var a= '12,13,14,15,16';
var b='p,q,q,p,q';
function getRepresentative(srcA, srcB, valA)
{
var mapIndexA = srcA && srcA.split(',').indexOf(valA);
var mapB = srcB.split(',');
return mapB && mapB[mapIndexA] || -1;
}
console.log(getRepresentative(a,b, '15'));
The function returns -1 if no corresponding map between A and B is found..
The following function takes the two strings and splits them with the comma, then iterates over the symbol-token pairings one by one. Whenever a new symbol is discovered, it gets added to symbols and an empty array is added to symbolToNumbers so that numbers for this symbol can be pushed onto the array.
At the end, we can iterate over symbols to display the list of numbers for each symbol. This code will work for any variety of symbols, not just 'p' and 'q'.
function findElements(numbers, symbols) {
var numberTokens = numbers.split(','),
symbolTokens = symbols.split(','),
symbolToNumbers = {},
symbols = [],
n = numberTokens.length;
if (n != symbolTokens.length) {
console.log('error: the lists must have the same length');
return;
}
for (var i = 0; i < n; ++i) {
var number = numberTokens[i],
symbol = symbolTokens[i];
if (symbolToNumbers[symbol] === undefined) {
symbols.push(symbol);
symbolToNumbers[symbol] = [];
}
symbolToNumbers[symbol].push(number);
}
for (var i = 0; i < symbols.length; ++i) {
var symbol = symbols[i],
numbers = symbolToNumbers[symbol];
console.log(symbol+': '+numbers.join(', '));
}
}
var a = '12,13,14,15,16';
var b = 'p,q,q,p,q';
findElements(a, b);
See this code running on JSFiddle: http://jsfiddle.net/0e1g2ryf/1/

How to convert arrays into an array of objects

Hi I'm trying to make an array of objects from several arrays.This is probably a very basic question, but I didn't find a proper way of doing it from searching online. :(
The original data I've got is
valueYes = [15,30,22,18,2,6,38,18];
valueNo = [23,75,45,12,45,9,17,23];
valueNotSure = [1,-1,1,1,-1,-1,-1,1];
What I want to achieve is an array like :
data = [object1, object2,.....]
Each object is made of :
object1 = {valueYes:15, valueNo:23,valueNotSure:1}
object2 = {valueYes:30, valueNo:75,valueNotSure:-1}
.......
my current code is a bit messy, which only return me an empty value of each key:
valueYes = [15,30,22,18,2,6,38,18];
valueNo = [23,75,45,12,45,9,17,23];
valueNotSure = [1,-1,1,1,-1,-1,-1,1];
var object1 = Object.create({}, {
myChoice: { value: function(myChoice) {for (var i = 0; i < len; i++){return this.myChoice[i] = myChoice[i];} } }
});
Assuming all your arrays have the same size:
valueYes = [15,30,22,18,2,6,38,18];
valueNo = [23,75,45,12,45,9,17,23];
valueNotSure = [1,-1,1,1,-1,-1,-1,1];
var data = [];
for(var i = 0; i < valueYes.length; i++){
data.push({
valueYes: valueYes[i],
valueNo: valueNo[i],
valueNotSure: valueNotSure[i]
});
}
You could use something like below;
var objs = valueYes.map(function (v, i) {
return {
valueYes: v,
valueNo: valueNo[i],
valueNotSure: valueNotSure[i]
};
});
... this uses the map() Array method, and assumes that all the arrays are the same length...
This?
var valueYes = [15,30,22,18,2,6,38,18];
var valueNo = [23,75,45,12,45,9,17,23];
var valueNotSure = [1,-1,1,1,-1,-1,-1,1];
var data = [];
valueYes.forEach(function(item, index) {
data.push({ valueYes: valueYes[index], valueNo: valueNo[index], valueNotSure: valueNotSure[index] });
});
console.log(data);
http://jsfiddle.net/chrisbenseler/9t1y1zhk/

Create an array [n,[v,..,z]] from a list of key-value pairs

I have this input sample:
var c1 = "s_A_3";
var c2 = "s_B_10";
var c3 = "s_B_9";
var c4 = "s_C_18";
var c5 = "s_C_19";
var c6 = "s_C_20";
Which can easily be concatenated to:
var keypairs = ["A_3","B_10","B_9","C_18","C_19","C_20"];
And I want to convert this to a multidimensional array like this:
var groupArray = [["A",[3]],["B",[10,9]],["C",[18,19,20]]];
It's like a kind of card-sorting. How can I achieve this?
Maybe something like this:
function makeGroups(arr) {
var result = [], prev;
for(var i = 0; i < arr.length; i++) {
var x = arr[i].split("_");
if (prev !== x[0]) {
prev = x[0];
result.push([prev, []]);
}
result[result.length - 1][1].push(x[1]); // or .push(parseInt(x[1], 10))
}
return result;
}
var keypairs = ["A_3","B_10","B_9","C_18","C_19","C_20"];
console.log(makeGroups(keypairs));
// [["A",["3"]],["B",["10","9"]],["C",["18","19","20"]]]
Demonstration
The above method assumes the groups will be contiguous (e.g. all B_ elements appear together). In case your input may be out of order, you can tweak this algorithm to still group all elements together regardless of where they appear in the input:
function makeGroups(arr) {
var result = [], keys = {};
for(var i = 0; i < arr.length; i++) {
var x = arr[i].split("_");
if (!(x[0] in keys)) {
keys[x[0]] = [];
result.push([x[0], keys[x[0]]]);
}
keys[x[0]].push(x[1]); // or .push(parseInt(x[1], 10))
}
return result;
}
var keypairs = ["A_3","B_10","C_18","C_19","C_20","B_9"];
console.log(makeGroups(keypairs));
// [["A",["3"]],["B",["10","9"]],["C",["18","19","20"]]]
Demonstration
When you need to mention "key value pairs" in a JS program, it's usually most appropriate to use... key value pairs =D.
function solution(input) {
var kvp = {},
result = [];
input.forEach(function (el) {
var cut = el.split("_"),
alpha = cut[0],
numeric = cut[1],
elsWithSameAlpha = kvp[alpha] = kvp[alpha] || [];
elsWithSameAlpha.push(numeric);
});
Object.keys(kvp).forEach(function (key) {
result.push([key, kvp[key]]);
});
return result;
}

Categories