Concatenate elements of an array Javascript - javascript

I have a list of hrefs with product data:name and it's id. First of all i removed prod Id that i'll use as separate variable.
After this, the remained part of href should be used as the product name.
var prodHref = document.querySelectorAll('.widget-products-list-item-label');
var allHref = [];
for(var i=0;i<prodHref.length;i++){
allHref.push(prodHref[i].href.split('/')[5])
}
var prodName = [];
for(var i=0;i<allHref .length;i++){
prodName.push(allHref [i].slice(0, -1))
}
var prodNameNew=[];
for(var i=0;i<prodName .length;i++){
prodNameNew.push(prodName[i].slice(0, -1))
}
So, the final result is on the attached screen. N
How i have concatenate all the elements of each array in order to get new arrays in the following format: Nokia G20 4 64 Albastru, Motorola G60 gri etc
Thank You

You want to capitalize the items of the inner arrays and then join them by space.
One way to do it is:
let result = arr.map(a => a.map(capitalize))
.map(a => a.join(" "))
where capitalize should be a function that takes a string and returns a string with first letter in upper case if possible.
You can find this in answers for the more specific SO question:
How do I make the first letter of a string uppercase in JavaScript?

Instead of 3 separate loops, we can get the substring based on single iteration only using Array.map() along with String.slice().
const prodHref = [{
href: "https://abc/def/ghi/alpha/mno"
}, {
href: "https://abc1/def1/ghi1/beta/mno1"
}, {
href: "https://abc2/def2/ghi2/gamma/mno2"
}, {
href: "https://abc3/def3/ghi3/omicron/mno3"
}];
const allHref = prodHref.map((obj) => obj.href.split('/')[5].slice(0, -2));
console.log(allHref);
Now you can use Array.join() method to join the result array.
const allHref = ["alp", "be", "gam", "omicr"];
console.log(allHref.join(" "));

Related

Javascript String splitting and Organizing based on first letter

I am currently working a project that I have to use js and php to retrieve data from the gateway. Now that i have retrieved it, but the data is not organised:
{"timestamp":1526524809413,"data":[
{"_id":"rJeixnNtpG","data":"N11B00074","raw":
[78,49,49,66,48,48,48,55,52],"timestamp":1525398515116},
{"_id":"HkzognEYpf","data":"N11E00000","raw":
[78,49,49,69,48,48,48,48,48],"timestamp":1525398515479},
{"_id":"BJxXp4t6M","data":"N11A00029","raw":
[78,49,49,65,48,48,48,50,57],"timestamp":1525398807747}
As you can see there are three types of data: the one starts with B(N11B00074), E(N11E00000) and A(N11A00029), followed by the 5 digits which is the data i wanted to split from the string while categorised by the type(B, E and A).
I have three tables in my web page and want to put the data into them based on the types: Like B being humidity table, A being temperature table and E being pH readings table.
So far i only managed to list them out in a table.
Is there a way that I can seperate the string and put them into an array based on their types?
You can use reduce to group objects in an array:
const input={"timestamp":1526524809413,"data":[{"_id":"rJeixnNtpG","data":"N11B00074","raw":[78,49,49,66,48,48,48,55,52],"timestamp":1525398515116},{"_id":"HkzognEYpf","data":"N11E00000","raw":[78,49,49,69,48,48,48,48,48],"timestamp":1525398515479},{"_id":"BJxXp4t6M","data":"N11A00029","raw":[78,49,49,65,48,48,48,50,57],"timestamp":1525398807747}]}
const arranged = input.data.reduce((accum, obj) => {
const { data } = obj;
const type = data[3];
const digits = data.slice(5);
if (!accum[type]) accum[type] = [];
accum[type].push({ ...obj, digits });
return accum;
}, {});
console.log(arranged);
// If you want an array and not an object:
console.log(Object.values(arranged));
If you want to group the array into an object. You can use reduce. You can get the fourth character of the string by using charAt
let arr = {"timestamp":1526524809413,"data":[{"_id":"rJeixnNtpG","data":"N11B00074","raw": [78,49,49,66,48,48,48,55,52],"timestamp":1525398515116}, {"_id":"HkzognEYpf","data":"N11E00000","raw": [78,49,49,69,48,48,48,48,48],"timestamp":1525398515479}, {"_id":"BJxXp4t6M","data":"N11A00029","raw":[78,49,49,65,48,48,48,50,57],"timestamp":1525398807747}]};
let result = arr.data.reduce((c, v) => {
let l = v.data.charAt(3); //Get the 4th chatacter
c[l] = c[l] || [];
c[l].push(v);
return c;
}, {});
console.log( result );

Split an object into array of objects based on a condition in JavaScript

How to split an object into array of objects based on a condition.
oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225}
Above is the given sample object. I want to make an array of objects like this,
newArray = [{"city":"Chicago", "similarTo":"Myrtle"},
{"city":"Portsmouth", "similarTo":"Rock Hill"},
{"city":"Columbia", "similarTo":"Laconia"},
{"city":"Council Bluffs", "similarTo":"Derry"}]
I have been scratching my head with this for a while now. How can I get the above array(newArray)?
Here is a bunch of code you can try.
1) Iterate over oldObject and get the name of the property.
2) Split that name into an array based on the ":" character, since it separates the cities
3) Go over that new array, splitting it on the "," character (so as not to get the states).
4) Put the values into the newObject, based on whether it's the first or second part of the original property name.
5) Push that newObject, now with items, into a newArray.
Basically, this parses apart the name and does some array splitting to get at the right values. Hope it helps and helps you understand too.
var oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225};
var newArray = [];
for (object in oldObject) {
var thisObjectName = object;
var thisObjectAsArray = thisObjectName.split(':');
var newObject = {
'city': '',
'similar_to': ''
};
thisObjectAsArray.forEach(function(element,index,array) {
var thisObjectNameAsArray = element.split(',');
var thisObjectNameCity = thisObjectNameAsArray[0];
if(index===0) {
newObject.city = thisObjectNameCity;
} else if(index===1) {
newObject.similar_to = thisObjectNameCity;
}
});
newArray.push(newObject);
}
console.log(newArray);
PS: to test, run the above code and check your Developer Tools console to see the new array output.

Search Json Array

I got a json array like below:
[
{"value":"uk-icon-adjust","title":"Adjust","url":"#", "text":""},
{"value":"uk-icon-adn","title":"Adn","url":"#", "text":""},
{"value":"uk-icon-align-center","title":"Align center","url":"#", "text":""},
{"value":"uk-icon-align-justify","title":"Align justify","url":"#", "text":""},
{"value":"uk-icon-align-left","title":"Align left","url":"#", "text":""}
]
I want to search this json array for specific titles. But the problem is, that I want to search with a Regex.
e.g: sb searchs for "ad" -> the function should return the first two json strings (Adjust and Adn).
I have no idea, now to setup a javascript function which can achieve this.
Some ideas?
Try this:
var array = [
{"value":"uk-icon-adjust","title":"Adjust","url":"#", "text":""},
{"value":"uk-icon-adn","title":"Adn","url":"#", "text":""},
{"value":"uk-icon-align-center","title":"Align center","url":"#", "text":""},
{"value":"uk-icon-align-justify","title":"Align justify","url":"#", "text":""},
{"value":"uk-icon-align-left","title":"Align left","url":"#", "text":""}
],
searchString = 'ad',
searchRegExp = new RegExp(searchString , 'i'); // 'i' makes the RegExp ignore case
var result = array.filter(function(e){ // Filter out any items that don't pass the
return searchRegExp.test(e.title); // RegExp test.
});
Result:
[
{"value":"uk-icon-adjust","title":"Adjust","url":"#","text":""},
{"value":"uk-icon-adn","title":"Adn","url":"#","text":""}
]
If you only want an array of titles, you can then map the result, like this:
var titles = result.map(function(e){
return e.title;
});
Titles:
["Adjust", "Adn"]
You'll want to do this mapping after filtering the array, for efficiency. This way you'll only have to iterate over the filtered result, instead of first iterating over all items to get the titles, then iterating over all of them again to filter them.
Of course, this can be combined with the filtering:
var result = array.filter(function(e){
return searchRegExp.test(e.title);
}).map(function(e){
return e.title;
});
Please keep in mind that both Array.prototype.filter() as Array.prototype.map() Aren't supported in IE 8 or lower. However, the pages I linked to do have some polyfills to make these functions work in older versions of IE.
That's an native Object. You can do it this way though, by first creating an Array of titles by using Array.map and then filter them using Array.filter
var titles = obj.filter(function(o){
return /^ad/i.test(o.title);
}).map(function(o){ return o.title; });
Amit Joki answer is the answer.
If you don't want to use map(), you could also try:
var json = [
{"value":"uk-icon-adjust","title":"Adjust","url":"#", "text":""},
{"value":"uk-icon-adn","title":"Adn","url":"#", "text":""},
{"value":"uk-icon-align-center","title":"Align center","url":"#", "text":""},
{"value":"uk-icon-align-justify","title":"Align justify","url":"#", "text":""},
{"value":"uk-icon-align-left","title":"Align left","url":"#", "text":""}
];
function search(array, re) {
var regexp = new RegExp(re, 'gi');
for (var i = 0; i < array.length; i++) {
return array[i].title.match(regexp);
}
throw "Couldn't find object like " + re;
}
console.info(search(json, 'ad'));

Formatting javascript array list into specific format using lodah\handlebar template or any other JS library

I have a JavaScript array which looks like this
var arr = ["[Dim1].[Mem1].&1","[Dim2].[Mem1].&2","[Dim1].[Mem1].&5","[Dim2].[Mem1].&77","[Dim3].[Mem1].&1"]
What I want: I want a string in this format
{
[Dim1].[Mem1].&1, [Dim1].[Mem1].&5
},
{
[Dim2].[Mem1].&2, [Dim2].[Mem1].&77
},
{
[Dim3].[Mem1].&1"]
}
I am able to do this by:
Loop over all the items in array & then split them with .&
Create another list based on [dim].[mem] combination. In our case the list will have [Dim3].[Mem1], [Dim1].[Mem1], [Dim2].[Mem1].
Now have two loop - One for every item in unique list and one for every item in original list & check if the item is original list contains the current item in unique list & then form the string.
Is there anyway to achieve this with the help of a template or handlebar template or any other JavaScript library?
You can use _.groupBy and Regular Expressions, to group the elements
var regExp = /\[(.*?)\]/g;
console.log(_.groupBy(arr, function(currentItem) {
var match, result = "";
while ((match = regExp.exec(currentItem)) !== null) {
result += match[1];
}
return result;
}));
Output
{ Dim1Mem1: [ '[Dim1].[Mem1].&1', '[Dim1].[Mem1].&5' ],
Dim2Mem1: [ '[Dim2].[Mem1].&2', '[Dim2].[Mem1].&77' ],
Dim3Mem1: [ '[Dim3].[Mem1].&1' ] }

Using concatenation and a passed parameter to loop through an array

var Animals = {
"Europe": { "weasel.jpg": "squeak", "cow.jpg": "moo"},
"Africa": { "lion.jpg": "roar", "gazelle.jpg": "bark"},
};
function region(a){
var b = "Animals."+a;
for(var index in b) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
newnode.src = index;
target.appendChild(newnode)
}
}
RELEVANT HTML
<li onclick="europe('Europe')">Europe</li>
Goal: on the click of the Europe <li>, pass the word Europe into my region function where it is then concatenated to produce Animals.Europe
This is in order to identify an array within the object structure at the top using the for(var index in Animals.Europe) loop. Why is the concatenation which produces Animals.Europe not treated in the same way as if I had typed this out?
In addition, you can see that I have used arrays to store an image source and description for different animals. Using my limited coding knowledge this was all I could think of. Is there an easier way to store image/description data in order to produce in HTML?
"Animals." + a is just a string value, e.g. "Animals.Europe", which is not the same thing as Animals.Europe. If you change the first line to var b = Animals[a];, you should be all set.
Edit: and as elclanrs pointed out, it should be region('Europe'), not europe('Europe').
Why is the concatenation which produces Animals.Europe not treated in the same way as if i had typed this out?
In this case the variable b is just a string ("Animals.Europe"), which is treated like any other string (i.e. a list of characters). This means that when you attempt to loop through it (for(index in b)) you will be looping over a simple list of characters.
What you can do instead is use the square brace notation of accessing an objects properties. This means you can instead write var b = Animals[a], retrieving attribute a from Animals. You can read more about working with objects in this way on this MDN page
You can access the europe property using the following
Animals[a]
Also you're calling a "europe" function when you should be calling "region"
You're not storing animals in arrays here, but in objects with the image names as keys. Usually you'll want to use relevant names as keys. For example if you want arrays of animals for each continent
var Animals = {
"Europe": [{
imageSrc: "weasel.jpg",
cry: "squeak"
},{
imageSrc: "cow.jpg",
cry: "moo"
}],
"Africa": [{
imageSrc: "lion.jpg",
cry: "roar"
},{
imageSrc: "gazelle.jpg",
cry: "bark"
}]
};
Now Animals['Europe'] gives an array of objects, where you could eventually store other properties. So if b is an array your loop will now look like:
var b = Animals['Europe'];
for(var i=0; i < b.length; i++) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
var animalData = b[i]; // The array item is now an object
newnode.src = animalData.imageSrc;
target.appendChild(newnode)
}

Categories