How to merge these complex JavaScript array objects? - javascript

Can someone help me to do these example?
var a = ["17","18"];
var b = ["1","1","1"];
I need an output below:
var c = [17:111,18:111]

var a = ["17","18"];
var b = ["1","1","1"];
var i=0;
var ConcateC="";
for(i=0;i< b.length;i++)
{
ConcateC +=b[i];
}
var c=[];
for(i=0;i< a.length;i++)
{
c[i]=a[i] + ":" + ConcateC;
alert(c[i]);
}

You can join the values of b together, then use map to create a new array from the indices of a:
var a = ["17","18"];
var b = ["1","1","1"];
var bValue = b.join("");
var c = a.map(function(currentValue) {
return currentValue + ":" + bValue;
});
console.log(c); // ["17:111","18:111"]

Related

Create an a multi diemensional array from different variables in 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);

How to flatten an array in Photoshop?

Here is my code :
var doc = app.activeDocument;
var allLayers = new Array;
var allLayers = collectAllLayers(doc, allLayers);
function collectAllLayers (doc, allLayers){
for (var m = 0; m < doc.layers.length; m++){
var theLayer = doc.layers[m];
if (theLayer.typename === "ArtLayer"){
allLayers.push(theLayer);
}else{
collectAllLayers(theLayer, allLayers);
}
}
return allLayers;
}
alert("array_layers : " + allLayers);
I am getting in alert array like this
[Layer1],[Layer2],[Layer3];
and I want make it looks like this :
[Layer1,Layer2,Layer3];
Thanks for answers and help in advance!
The code in question already works correctly. Referring to the documentation on ArtLayer, you can prove this by printing some of the properties for each of the objects in the array:
function collectAllLayers (layerSet, layers){
for (var i = 0; i < layerSet.layers.length; i++){
var layer = layerSet.layers[i];
if (layer.typename === "ArtLayer"){
layers.push(layer);
} else {
collectAllLayers(layer, layers);
}
}
return layers;
}
function printable (artLayers) {
var layerDescriptions = [];
for (var i = 0; i < artLayers.length; i++) {
var layer = artLayers[i];
layerDescriptions.push(
'{ name: ' + layer.name +
', kind: ' + layer.kind +
', opacity: ' + layer.opacity +
', visible: ' + layer.visible +
' }'
);
}
return layerDescriptions;
}
var artLayers = collectAllLayers(app.activeDocument, []);
var layerDescriptions = printable(artLayers);
alert(layerDescriptions);
Code in the question do display single level array of ArtLayer objects. One can be confused, because toString method of ArtLayer object returns name of the layer in square brackets (in version of PS that I have installed (v19.1.5), "ArtLayer" string is displayed before layer name, but still inside square brackets). For example:
var doc = app.activeDocument;
alert(doc.layers[0]); // Alerts "[ArtLayer Layer 1]"
To flatten array ary you can use [].concat.apply([], ary), like in:
var ary = [1, ["A", "B", "C"], 3];
alert(ary[2]); // Alerts "3"
alert([].concat.apply([],ary)[2]); // Alerts "B"
How about using the allLayers.push(theLayer[0]); instead of allLayers.push(theLayer);.
Have you tried to flat the list in the recursive result?
var doc = app.activeDocument;
var allLayers = new Array;
var allLayers = collectAllLayers(doc, allLayers);
function collectAllLayers (doc, allLayers){
for (var m = 0; m < doc.layers.length; m++){
var theLayer = doc.layers[m];
if (theLayer.typename === "ArtLayer"){
allLayers.push(theLayer);
}else{
flatten(collectAllLayers(theLayer, allLayers));
}
}
return flatten(allLayers);
}
function flatten(arr) {return arr.reduce(
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
)};
alert("array_layers : " + allLayers);
you can use
const flatten = (layers, allLayers) => layers.reduce((acc,layer) => (Array.isArray(layer)) ? collectAllLayers(layer, acc) : acc.push(layer), allLayers);
const collectAllLayers = (doc, allLayers) => flatten(doc.layers, allLayers);

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/

JavaScript split string in to two variables at character by number

How to split a string at a specific point defined by a number?
In example generate two variables, t1 and t2 from the string '123456' and have it split at character 3 so t1's value is '123' and t2's value is '456'...
var s0 = '123456';
console.log(s1);//123
console.log(s2);//456
I'd suggest:
var s0 = '123456',
t1 = s0.substring(0, s0.indexOf(3) + 1),
t2 = s0.substring(s0.indexOf(3) + 1);
References:
String.prototype.indexOf().
String.prototype.substring().
If you meant the 3rd character:
var ch = 3;
var s0 = "123456";
var s1 = s0.substr(0,ch); // will be '123'
var s2 = s0.substr(ch); // will be '456'
You can just do this.
var s0 = '123456';
var arr = s0.split('3');
var t1 = arr[0] + '3', t2 = arr[1];
Something like:
var foo = '123456'
,bar = [foo.slice(0,3), foo.slice(3)];
//=> bar now ["123", "456"]
Extend the String prototype:
String.prototype.splitAt = function(n) {
return n && n < this.length
? [this.slice(0,n), this.slice(n)]
: this;
}
// usages
'123456'.splitAt(3); //=> ['123', '456']
'123456'.splitAt(2); //=> ['12', '3456']
'123456'.splitAt(12); //=> '123456'
'123456'.splitAt(); //=> '123456'
Try
var s0 = "123456"
, s1 = s0.slice(0, 3); // first 3 characters in string , `123`
, s2 = s0.slice(- (s0.length - s1.length) ); // remainder of string , `456`(+)
console.log(s0, s1, s2)
var s = '123456';
var sos = 3;//number to split by
var t1 = '';
var t2 = '';
for (var i = 0; i < s.length; i++)
{
if (i<sos) {t1 += s[i];}
else {t2 += s[i];}
}
console.log('t1 = '+t1);
console.log('t2 = '+t2);

Dynamically generated object not working as parameter to .css()

I have this function:
function myfunc(obj, properties, value) {
$.each(properties, function(i, key) {
var a = '-webkit-border-' + key + '-radius';
var b = '-moz-border-radius-' + key.replace(/\-/g, '');
var c = 'border-' + key + '-radius';
var z = value+'px';
obj.css({a : z, b: z, c: z});
});
}
Called like this:
myfunc($tab, ['top-left', 'top-right'], defaults.tabRounded);
Note that if I replace the obj.css line with:
obj.css({'border-top-right-radius': value+'px'});
It works as intended. Yet the values of a, b, c are completely correct.
What is going on?
The keys of an object literal in JavaScript are strings, not variables. If you do not quote them yourself, they are auto-quoted. So if you write
var a = {b: 1};
it's the same as if you had written
var a = {'b': 1};
You have to use [] to set keys dynamically.
var a = {};
a[b] = 1;
In this case modify your function to
function myfunc(obj, properties, value) {
$.each(properties, function(i, key) {
var a = '-webkit-border-' + key + '-radius';
var b = '-moz-border-radius-' + key.replace(/\-/g, '');
var c = 'border-' + key + '-radius';
var z = value+'px';
var css = {};
css[a] = css[b] = css[c] = z;
obj.css(css);
});
}

Categories