Initialise an array with same value, x times - javascript

If I have:
let a = [1,3,4,5];
how do I dynamically set b to have the same length as a with each entry containing "<", i.e.
Expected result:
b = ["<","<","<","<"];

You can use Array#map:
const a = [1,3,4,5];
const b = a.map(() => "<");
console.log(b);
You can use Array#from:
const a = [1,3,4,5];
const b = Array.from(a, () => "<");
console.log(b);
Or you can use Array#fill:
const a = [1,3,4,5];
const b = new Array(a.length).fill("<");
console.log(b);

Here's a solution:
Array(a.length).fill('<');

Related

how to convert string array of objects to array of objects

I have an array that I want to convert but I have no idea how to do it
how can i convert this array
const a = ['{/run:true}', '{/sleep:false}'];
in this array
const b = [{'/run':true}, {'/sleep':false}];
Using map and a regular expression:
const a = ['{/run:true}', '{/sleep:false}'];
const b = a.map(s => {
const [_,k,v] = s.match(/\{(.+):(.+)}/);
return {[k]: JSON.parse(v)};
});
console.log(b);
Or other way is to run a sting replacement and JSON.parse
const a = ['{/run:true}', '{/sleep:false}'];
const b = JSON.parse("[" + a.toString().replace(/\{([^:]+)/g, '{"$1"') + "]");
console.log(b);
Created this simple function to do exactly that
const a = ['{/run:true}', '{/sleep:false}'];
// desired output
const b = [{ run: true }, { sleep: false }];
const c = a.map(item => {
const key = item.match(/\w+/)[0];
const value = item.match(/true|false/)[0];
return { [key]: value === 'true' };
});
console.log(c);
const a = ['{/run:true}', '{/sleep:false}'];
const output = a.map(item => {
const normalize = item.replaceAll("{", "").replaceAll("}", "")
const splitedStr = normalize.split(':');
const key = splitedStr[0];
const value = splitedStr[1];
return {[key]: value}
})
console.log(output)
const a = ['{/run:true}', '{/sleep:false}'];
const c = a.map(item => {
return {
['/' + item.split(':')[1].split('{')[0]]: item.split(':')[1].split('}')[0]
};
});
console.log(c);

Return one element array or empty array best practice in JavaScript

Is there any better way to implement this?
const a = _.get(obj, 'property');
const b = a ? [a] : [];
obj is an object, may or may not have property. If it does, return an array of one element of property, else return an empty array.
const obj = {
prop: "hello"
}
const b = obj.hasOwnProperty("prop") ? [obj.prop] : [];
let obj = {}
console.log("when property is not present: ", obj["property"] || [])
obj = {property: ["hello"]}
console.log("when property is present: ", obj["property"] || [])
You could wrap it into array an filter non-nil value
const a = _.get(obj, 'property');
const b = [a].filter(Boolean);
const a1 = null
const a2 = 1
const res1 = [a1].filter(Boolean)
const res2 = [a2].filter(Boolean)
console.log(res1)
console.log(res2)

How to group different letters (not necessarily consecutive) using a regex

The example below results as expected:
const str = "abbcccddddeeeeeffffff";
const res = str.match(/(.)\1*/g);
console.log(res);
But if I try to group non consecutive letters:
const str = "abxbcxccdxdddexeeeefxfffffxx";
const res = str.match(/(.)\1*/g);
console.log(res);
I would like to get somethig like this:
[ 'a', 'bb', 'xxxxxxx', 'ccc', 'dddd', 'eeeee', 'ffffff']
Sort the string before applying the Regex :
const str = "abxbcxccdxdddexeeeefxfffffxx";
const res = [...str].sort().join('').match(/(.)\1*/g);
console.log(res);
If you absoloutely want them in that order, you can dedup the string and match the letters individually
const str = "abzzzbcxccdxdddexeeeefxfffffxx";
const res = [];
[...new Set(str)].forEach(letter => {
const reg = new RegExp(`${letter}`, "g");
res.push(str.match(reg).join(""));
});
console.log(res);
Here is way to do it without a regex, but you will need an array to hold the results:
var a = []; // (scratch space)
Array.prototype.map.call("abxbcxccdxdddexeeeefxfffffxx", c => c.charCodeAt(0))
.forEach(n => a[n] ? a[n] += String.fromCharCode(n) : a[n] = String.fromCharCode(n));
console.log(a.join(''));
Outputs: "abbcccddddeeeeeffffffxxxxxxx"
And if you need it in order, you can add m to keep a mapping of positions:
var a = [], m = []; // (scratch space; m maps chars to indexes)
Array.prototype.map.call("abxbcxccdxdddexeeeefxfffffxx", c => c.charCodeAt(0))
.forEach(n => (!m[n]&&(m[n]=m.length), a[m[n]] ? a[m[n]] += String.fromCharCode(n) : a[m[n]] = String.fromCharCode(n)));
console.log(a.join(''));
Outputs: "abbxxxxxxxcccddddeeeeeffffff"

seperate comma seperated string values in string variable

I am trying to extract the string which is like
var str = "[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]"
Desired ouput
a = "/home/dev/servers"
b = "e334ffssfds245fsdff2f"
Here you are:
const str = "[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]";
const object = JSON.parse(str);
const a = object[0];
const b = object[1];
console.log(a);
console.log(b);
The following will work fine for you.
var str = "[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]";
var foo = JSON.parse(str); //Parse the JSON into an object.
var a = foo[0];
var b = foo[1];
Using JSON.parse()
let [a, b] = JSON.parse("[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]")
console.log(a)
console.log(b)

How to copy existing properties of an object to another one in angular?

Consider the following code:
const x={name:"a"};
const y={name:"b", fname:"c"};
const z = Object.assign(x,y); //output: z={name:"b", fname:"c"}
//expected: {name:"b"}
How to achieve the expected result?
You can use for...in loop
const x={name:"a"};
const y={name:"b", fname:"c"};
const z = {};
for (let key in x) z[key] = y.hasOwnProperty(key) ? y[key] : x[key];
console.log(z);
Object.prototype.customAssign = function(x,y){
let item = {};
Object.keys(x).forEach(function(a,b){
destiKeys.indexOf(a)>=0? item[a] = y[a] : null;
});
return item;
};
const x={name:"a"};
const y={name:"b", fname:"c"};
const z = Object.customAssign(x,y); //output: z = {name:"b"}
use spreadOperator https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
z={...x,..y} //All properties of x + All properties of y
//y properties replace the sames properties of x

Categories