Trim Array value from specific char to specific char - javascript

How to get specific value from array?
i.e.
"Names": [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
Output must be:
"Names": [
"name",
"Type",
"Option",
"Pointer"
]

Try like this:
export class AppComponent {
Names = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
constructor() {
var modifiedNames = this.Names.map(x => x.split('[').pop().split(']')[0])
console.log(modifiedNames)
}
}
See Stackbiltz Demo

const array = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
];
const newArray = array.map(e => /^\w+\[(\w+)\]$/.exec(e)[1]);
// ["name", "Type", "Option", "Pointer"]

You can use substring method and based on the start and end bracket grab the subtring. To iterate on every element of array use map function, it creates a new array with the results of calling a provided function on every element in the calling array.
const arr = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
let result = arr.map((a)=>{ return a.substring(a.indexOf("[") + 1 , a.indexOf("]")) });
console.log(result);

You can loop through array and using following regex to get the desired output.
const array = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
];
var regexTest = new RegExp(/\[([^\]]+)\]/);
var newArray = array.map(e => regexTest.exec(e)[1]);
fiddle link

substring and indexOf in action:
let newArray = [];
for(var i=0; i<array.length; i++){
var s = array[i];
var n = s.indexOf('[');
s = s.substring(n+1, s.length-1);
newArray.push(s);
}
OR
let newArray = [];
for(var i=0; i<array.length; i++){
newArray.push(array[i].substring(array[i].indexOf('[')+1, array[i].length-1));
}

Related

Convert object into 2-d array but remove keys

I am trying to convert the below this:
let JSON = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{10:"hello4",11:"goodbye4",12:"bonjour4"}
]
to this:
let arr = [
["hello","goodbye","bonjour"],
["hello2","goodbye2","bonjour2"],
["hello3","goodbye3","bonjour3"],
["hello4","goodbye4","bonjour4"]
]
I have tried:
var row1 = JSON.map(function(e) {
return [ e.1, e.2, e.3];
});
var row2 = JSON.map(function(e) {
return [ e.4, e.5, e.6];
});
var row3 = JSON.map(function(e) {
return [ e.7, e.8, e.9];
});
var row4 = JSON.map(function(e) {
return [ e.10, e.11, e.12];
let array = [row1,row2,row3,row4]
But cannot get anything working. I would appreciate any help :)
Try this one:
let JSON = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{10:"hello4",11:"goodbye4",12:"bonjour4"}
];
let arr = JSON.map(obj => {
return Object.values(obj);
});
You can use a standard for loop to iterate the object key's and push the object values into an array(ordered) which you return, all within the callback of Array.map. Also, your problem is that Array.map works on every item of the array, not just one at a time. that is why your code doesn't work the way you expected.
let JSON = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{10:"hello4",11:"goodbye4",12:"bonjour4"}
]
const result = JSON.map(a=>{
const b = [];
for(var k in a){
b.push(a[k]);
}
return b;
});
console.log(result);
Given your sample data, it seems you could simply use Object.values:
let original = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{10:"hello4",11:"goodbye4",12:"bonjour4"}
]
var array = original.map(Object.values);
console.log(array);
This works because the order of elements in each object is the same as the order you want to achieve in the result array.
If you this is not always the case (e.g. you have {12:"bonjour4",11:"goodbye4",10:"hello4"} and you still want to return ["hello4","goodbye4","bonjour4"]) you can sort entries by their keys first. For example:
let original = [
{1:"hello",2:"goodbye",3:"bonjour"},
{4:"hello2",5:"goodbye2",6:"bonjour2"},
{7:"hello3",8:"goodbye3",9:"bonjour3"},
{12:"bonjour4",11:"goodbye4",10:"hello4"}
]
var array = original
.map(obj => Object
.entries(obj)
.sort(([k1], [k2]) => k1 - k2)
.map(([_, v]) => v));
console.log(array);
As a side note, I'd caution you against using the name JSON since this will hide the built-in JSON object.

How to push values to new array by comparing 2 arrays

I have 2 arrays.
selectedgroup = [ ID:1, selected:true,
ID:2, selected:false,
..... ]
The 2nd array is,
mainarr=[ ID:1, mainid:25, name:ser, pID:545,
ID:2, mainid:84, name:ferdi, pID:678,
ID:3, mainid:88, name:ferSER, pID:656,
....]
I want to check if mainarr contains an element of selectedgroup. The unique id in both arrays is ID . Then I want to push it on a new array.
How can I do this?
Assuming your array is in following valid format. Iterate over your mainarr and check if ID of mainarr matches the ID of selectedgroup array then simply push the object into new array. Like following:
var selectedgroup = [ {ID:1, selected:true},{ID:2, selected:false} ];
var mainarr = [ {ID:1, mainid:25, name:'ser', pID:545},{ID:2, mainid:84, name:'ferdi', pID:678},{ID:3, mainid:88, name:'ferSER', pID:656}];
var newArray = [];
mainarr.forEach(function(mainObject) {
for (let i=0; i<selectedgroup.length; i++){
if(selectedgroup [i].ID === mainObject.ID){
newArray.push(mainObject);
}
}
});
console.log(newArray);
Try this
var newarr =[];
for(i=0; i<mainarr.length; i++){
for(j=0;j<selectedgroup.length; j++){
if(mainarr[i].ID = selectedgroup[j].ID)
{
newarr.push(mainarr[i]);
}
}
}
I think use of filter, is a better method than use of forEach. So I just include this solution for reference.
var selectedgroup = [ {ID:1, selected:true},{ID:2, selected:false} ];
var mainarr = [ {ID:1, mainid:25, name:'ser', pID:545},{ID:2, mainid:84, name:'ferdi', pID:678},{ID:3, mainid:88, name:'ferSER', pID:656}];
const selectedgroupIds = selectedgroup.map(selected => selected.ID);
const newarr = mainarr.filter(main => {
return selectedgroupIds.indexOf(main.ID) !== -1;
})
Array.prototype.filter() method creates a new array with all elements that pass the test implemented by the provided function. Like following:
var selectedgroup = [ {ID:1, selected:true},{ID:2, selected:false} ];
var mainarr = [ {ID:1, mainid:25, name:'ser', pID:545},{ID:2, mainid:84, name:'ferdi', pID:678},{ID:3, mainid:88, name:'ferSER', pID:656}];
var newarr = mainarr.filter(function(eachArr){
for (var i = 0; i < selectedgroup.length; i++){
if(selectedgroup [i].ID === eachArr.ID){
return true;
} }})
If selectedgroup array can have many values, you can use map to get all ids first to avoid inner loop and then filter with them as #CHANist said.
For your reference: Array.prototype.map().
Thus, the code would become
var selectedgroup = [ {ID:1, selected:true},{ID:2, selected:false} ];
var mainarr = [ {ID:1, mainid:25, name:'ser', pID:545},{ID:2, mainid:84, name:'ferdi', pID:678},{ID:3, mainid:88, name:'ferSER', pID:656}];
var ids = selectedgroup.map(function(obj){ return obj.ID});
var newarr = mainarr.filter(function(eachArr){
for (var i = 0; i < selectedgroup.length; i++){
if(ids.indexOf(eachArr.ID) !== -1){
return true;
} }})
Use below code,
var selectedgroup = [
{ID:1, selected:true},
{ID:2, selected:false}
];
var mainarr = [
{ID:1, mainid:25, name:'ser', pID:545},
{ID:2, mainid:84, name:'ferdi', pID:678},
{ID:3, mainid:88, name:'ferSER', pID:656}
];
var newArray=[];
for (var i = 0, l2 = mainarr .length; i < l2; i++) {
for (var j = 0, l1 = selectedgroup .length; j < l1; j++) {
if(mainarr [i].ID===selectedgroup [j].ID){
newArray.push(mainarr [i]);
}
}
}
console.log(newArray);

combine multiple list to single array

{ "data": [ {"firstName": "Achmad"}, {"lastName": "a"} ] } and this my script var body = request.body;for(var i = 0;i < body.data.length;i++){var obj = body.data[i];var keyes = Object.keys(obj);} the problem response from var keyes = Object.keys(obj); is list like this [ 'firstName' ] [ 'lastName' ] i'm wanna like this ['firstName', 'lastName']
Thanks before.
Assuming each of the arrays are elements of a parent array, one way you could achieve this is by using Array.prototype.reduce:
const flat = [
["aku"],
["dia"],
["ia"]
].reduce((accum, el) => accum.concat(el), [])
console.log(flat);
EDITED: You could concat each item of your array :
const body = {
"data": [
{"firstName": "Achmad"},
{"lastName": "a"}
]
};
let result = [];
for (item of body.data) {
result = result.concat(Object.keys(item));
}
console.log(result); // -> ['firstName', 'lastName']
Maybe you want to do something like this
var body = request.body;
var keyes = [];
for(var i = 0; i < body.data.length; i++){
var obj = body.data[i];
keyes.push( Object.keys(obj) );
}

Flat array to multi dimensional array (JavaScript)

I have the following array:
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"];
I want to have the following output:
var desiredOutput = [{
"CONTAINER": [{
"BODY": [{
"NEWS": [{
"TITLE": []
}]
}]
}]
}];
How can I achieve this in JavaScript?
Already tried with recursive loop, but it does not work, gives me undefined.
dataChange(sampleArray);
function dataChange(data) {
for (var i = 0; i < data.length; i++) {
changeTheArray[data[i]] = data[i + 1];
data.splice(i, 1);
dataChange(changeTheArray[data[i]]);
}
}
Thanks
This does what you're asking for, in one line, and with no additional variables:
let desiredOutput = sampleArray.reduceRight((obj, key) => [ { [key]: obj } ], []);
The reduceRight call, starting from the right hand end of the array, progressively accumulates the current data (seeded with the initial value of []) as the value of the single key in a new object { [key] : _value_ } where that object is itself the single entry in an array [ ... ].
This will do it:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => { // For every entry, named `key` in `sampleArray`,
const next = []; // New array
current.push({[key]: next}); // Add `{key: []}` to the current array,
current = next; // Move the pointer to the array we just added.
});
console.log(data);
{[key]: next} is relatively new syntax. They're computed property names.
This:
const a = 'foo';
const b = {[a]: 'bar'};
Is similar to:
const a = 'foo';
const b = {};
b[a] = 'bar';
You could re-write the forEach as a one-liner:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => current.push({[key]: current = [] }));
console.log(data);
This current.push works a little counter-intuitively:
Construct a new element to push. This assigns a new value to current.
Push the new element to the reference .push was called on.
That reference is the value of current before current = [].
Hi i made a little demo :
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"
],
generateArray = [],
tmp = null;
for(var i = 0; i < sampleArray.length; i++) {
if(tmp===null){
generateArray[sampleArray[i]] = {};
tmp = generateArray[sampleArray[i]];
}else{
tmp[sampleArray[i]] = {};
tmp = tmp[sampleArray[i]];
}
}
console.log(generateArray);

Split array of string with multiple delimiters and store in separate arrays

I have a Javascript object like
Object = { "ratio1" : "12+45*36",
"ratio2" : "34+45*16",
"ratio3" : "17+25"}
I am trying to split the values like the values before + in one array and values after + in one array . so the output should be like
Array1= ["12" , "34" , "17"]
Array2 = ["45" , "36" , "45","16","25"].
To perform this I am iterating through the keys and getting the values first then I am again iterating through the values array I am splitting it using
ratioArray.split("+");
This gave me [[" 12" , "45*36"], [" 34", "45*16"], [" 17", "25"]]
Now again I have iterate through all the three arrays and split using second delimiter. Is there any efficient way to perform this so that I can reduce these many iterations
const ratios = {
"ratio1" : "12+45*36",
"ratio2" : "34+45*16",
"ratio3" : "17+25"
}
const nums = Object.keys(ratios)
.map(key => ratios[key]
.replace(/[+*]/g, '|')
.split('|')
)
const [ array1, array2, array3 ] = nums
document.querySelector('pre').innerText =
`array1 === [${array1}]\n` +
`array2 === [${array2}]\n` +
`array2 === [${array3}]\n`
<pre />
var Object = {
"ratio1": "12+45*36",
"ratio2": "34+45*16",
"ratio3": "17+25"
}
var Array1 = [],
Array2 = [],
temp;
for (var key in Object) {
temp = Object[key].split('+');
Array1.push(temp[0])
temp = temp[1].split('*')
for(var i = 0; i < temp.length; i++){
Array2.push(temp[i])
}
}
console.log('Array1:['+Array1[0]+','+Array1[1]+','+Array1[2]+']')
console.log('Array2:['+Array2[0]+','+Array2[1]+','+Array2[2]+','+Array2[3]+','+Array2[4]+']')
You can do something like this.
object = {
"ratio1": "12+45*36",
"ratio2": "34+45*16",
"ratio3": "17+25"
}
var array1 = [],
array2 = [];
for (var key in object) {
var _o = object[key].split("+");
array1.push(_o[0]);
_o[1].split("*").forEach(function(num) {
array2.push(num);
})
};
console.log("array 1", array1);
console.log("array 2", array2)

Categories

Resources