Array not giving expected answer using split function - javascript

In this code console.log (name[i]) results in first character of split string(i.e. c ,s,t) but i want name separate like chris. and its giving the expected result on MDN but not on console on js.
var char=['chris:2255655','sarrah:5456454','taur:5655226'];
var name=new Array();
for(var i=0;i<char.length;++i){
name=char[i].split(':');
console.log(name[i]);
}

Your code should look like
var char=['chris:2255655','sarrah:5456454','taur:5655226'];
for(var i=0;i<char.length;++i){
var w = char[i].split(":");
console.log(w[0]);
}
Please check my snippet. It seems that your split was not resulting an array but a string. So you were getting only the first symbol

You can simply do:
var char=['chris:2255655','sarrah:5456454','taur:5655226']
// As array
console.log(char.map(x => x.split(':')[0]))
// As a string
console.log(...char.map(x => x.split(':')[0]))
We are using map to go through each of the strings and split on :.
Since split gives us an array we take the 0 index which contains the name. Since Map returns an array you can either leave as is or destructure it with ... to get its contents.

You can do like this.
const char=['chris:2255655','sarrah:5456454','taur:5655226'];
const name= [];
for(let i=0;i<char.length;i++){
let val =char[i].split(':');
name.push(val[0]);
console.log(name[i]);
}

Since you know the position of your selection you can assign directly to a variable:
var char = ['chris:2255655', 'sarrah:5456454', 'taur:5655226']
var names = char.map(item => {
var [name] = item.split(':'); // <- select only first index
// var [name, id] = item.split(':'); // <- select first and second index
// var [name, ...rest] = item.split(':'); // <- select first and rest of the elements
// var [name,] = item.split(':'); // <- select first and skip next element index using ","
return name;
})
console.log(names);

Related

How to remove all characters before specific character in array data

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}

Get multiple values from hash in URL

www.domain.com/lookbook.html#look0&product1
On page load I would like to grab the whole hash ie. #look0&product1
then split it up and save the number of the look ie 0 in a variable called var look and the number of the product ie 1 in another variable called var product. Not sure how to achieve this.
Is this also the best way of passing and retrieving such parameters? Thanks
Use var myHash = location.hash to get hash part of URL. Than do var params = myHash.split('&') and after that for each part do part.split('=') to get key-value pairs.
Maybe it's better to pass these parameters via GET from PHP side and than post them inside page when page is processed via PHP?
<input type="hidden" name="look" value="<?php echo isset($_GET['look']) ? $_GET['look'] : '';?>"/>
Here's the pure Javascript method:
function parseHash(hash) {
// Remove the first character (i.e. the prepended "#").
hash = hash.substring(1, hash.length);
// This is where we will store our properties and values.
var hashObj = {};
// Split on the delimiter "&" and for each key/val pair...
hash.split('&').forEach(function(q) {
// Get the property by splitting on all numbers and taking the first entry.
var prop = q.split(/\d/)[0];
// Get the numerical value by splitting on all non-numbers and taking the last entry.
var val_raw = q.split(/[^\d]/);
var val = val_raw[val_raw.length - 1]
// If the property and key are defined, add the key/val pair to our final object.
if (typeof prop !== 'undefined' && typeof val !== 'undefined') {
hashObj[prop] = +val;
}
});
return hashObj;
}
Use like:
parseHash(window.location.hash /* #book10&id1483 */)
/* returns: Object {book: 10, id: 1483} */
I suggest using the norm for passing values through the location's hash: prop=value. Ex: #book=10&id=311. Then you can easily split on = for each property.
You can use .match(re) method with use of regular expression to extract the number from the given string.
You can try this:
var hashes = location.hash.split('&'); // get the hash and split it to make array
var values = hashes.map(function(hash){ // use .map to iterate and get a new array
return hash.match(/\d+/)[0]; // returns the numbers from the string.
});
var loc = "look0345345345&product1";
var hashes = loc.split('&');
var values = hashes.map(function(hash){ return hash.match(/\d+/)[0]; });
document.body.innerHTML = '<pre>'+ JSON.stringify(values) + '</pre>';
You could try this:
var url = 'www.domain.com/lookbook.html#look0&product1'
, result = {}
, expr = RegExp(/[#&]([a-zA-z]+)(\d+)/g);
var parts = expr.exec(url);
while(parts != null && parts.length == 3) {
result[parts[1]] = parts[2];
parts = expr.exec(url);
}
var look = result['look']
, product = result['product'];
document.getElementById('result').innerHTML = 'look = ' + look + '<br>' + 'product = ' + product;
<p id='result'></p>
We are basically using a regular expression to divide the parameter name and value into two groups that we can then get by calling expr.exec(url).
Each time we call expr.exec(url), we get the next set of name and value groups.
We set the value of the parameter to its name in the result object.
In the regular expression /[#&]([a-zA-z]+)(\d+)/g, the g after the /.../ means match each time find the two groups.
The two groups are prefaced by either & or # ([#&]). The first group is a String of letters ([a-zA-z]+), the name of the parameter. The second is a String of numbers (\d+), the value you are looking for.
The regex returns the String that matches the pattern as the first result in the parts array, followed by the groups matched, which which means that our two groups in each iteration will be parts[1] and parts[2].
you should use:
function parseHash(hash){
hash = hash.substring(1, hash.length); //remove first character (#)
var obj ={}; //create the output
var qa = hash.split('&'); //split all parameters in an array
for(var i = 0; i < qa.length; i++){
var fra1 = qa[i].split('='); //split every parameter into [parameter, value]
var prop = fra1[0];
var value = fra1[1];
if(/[0-9]/.test(value) && !isNaN(value)){ //check if is a number
value = parseInt(value);
}
obj[prop] = value; //add the parameter to the value
}
return obj;
}
document.querySelector("input.hash").onkeyup = function(){
console.log( parseHash(document.querySelector("input.hash").value));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="hash"/>
<p class="output"></p>
use as
parseHash(location.hash /* #look=0&product=1 );
/returns {look: 0, product: 1}/

How to get string in regular expression with space

This is my input as string
'controls: ["aa.bb.cc","dd.ee.ff"],elements: []'
I want to get the result of the data in the controls meaning :
"aa.bb.cc","dd.ee.ff"
I tried pattern
/.*(controls:.*).*/
but I didn't get all the result
I think my problem is becuase the new line
You can do it with regEx
var c = 'controls: ["aa.bb.cc", "dd.ee.ff"], elements: []';
var match = c.match(/("[a-z.]+")/g);
// or c.match(/([a-z][a-z][.][a-z][a-z][.][a-z][a-z])/);
// to strictly match letters . letters . letters
// or for a shorter match: c.match(/(\w+[.]\w+[.]\w+)/);
console.log(match); // an array of your values
EDIT:
if you only want to get the values in controls and not element, you can get the controls values out with the regEx /controls: ([\["a-z., \]]+,)/g
You could simply parse your input as a JSON object then loop throught the controls array:
var input='controls: ["aa.bb.cc", "dd.ee.ff"],
elements: []';
json = JSON.parse(input);
var controls=json.controls;
//then loop throught the controls values
for(var i=0;i<controls.length;i++){
console.log(controls[i]);
}
I think that should do it.
This might look like a very crude solution, but it works.
This expression will give you aa.bb.cc :
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[1]
and this will give the next element i.e. dd.ee.ff
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[2]
In general,
var str = "controls: [\"aa.bb.cc\",\"dd.ee.ff\"],elements: []";
var resLength = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/).length;
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/);
for (var i=1; i<resLength; i++) {
console.log(res[i]);
}

Split function going Abnormal in JavaScript

This is the Contents of file from where i am reading...
aaa 3333,bbb 5,ccc 10
I am getting un defined for the keyvalue[2], [3], [4] and [5]. Why is it so???
I am actually first spliting based on , and then based on space.
because you split by comma first, so item is now 'PrimeSuiteId 3333'. When you split that by space you get two items only, so 3rd value (keyvalue[2]) and above is empty.
Edit: possible fix to make second part of your script work
swap
var items = contents.toString().split(',');
with
var items = contents.toString().replace(/,/,' ');
which will simply replace commas with spaces in the original string so your array of expected values matches up
Another edit: because splitting by comma or space is better (as in comments)
var contents = f.read();
Ti.API.info(contents);
var items = contents.toString(); // changed to return complete string not split
// removed for loop altogether
var keyvalue = items.split(/,|\s/); // changed to split by comma or space
var AppointmentSearchDaysAfter = keyvalue[0];
var AppointmentSearchDaysAfterValue = keyvalue[1];
var AppointmentSearchDaysBefore = keyvalue[2];
var AppointmentSearchDaysBeforeValue = keyvalue[3];
var PrimeSuiteId = keyvalue[4];
var PrimeSuiteIdValue = keyvalue[5];
From the contents in the contents file you should only be able to get values for
var AppointmentSearchDaysAfter = keyvalue[0];
var AppointmentSearchDaysAfterValue = keyvalue[1];
You only have one space for each data entry between the commas
Split function is working fine, you are expecting it to behave abnormal.
You will get only two values in array after split by space. From where will it bring 6 values!!!?
The rest values you will get in next iterations.
Instead of declaring individual variables for each item and then loading them from the contents string, you can reduce the whole thing to an object with key/value pairs:
var items = contents.split(',').reduce(function (acc, val) {
var split = val.split(' ');
return acc[split[0]] = split[1], acc;
}, {});
To test what the values are, try:
console.log(items.PrimeSuiteId); // outputs 3333
console.log(items.AppointmentSearchDaysBefore); // outputs 5
console.log(items.AppointmentSearchDaysAfter); // outputs 10

Remove items from based of substring in array jquery

This might seems a very newbie sort of question, but I am struggling with this as of now and seek some help.
Here is a example array in JavaScript
var SelectedFilters = ["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]", "[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
Now I wish to remove certain items from this array based on a search term, now the search term contains only a part of string such as
var searchTerm1 = 'size'
var searchTerm2 = 'color'
I have already tried the following code, but its not working:
var i = SelectedFilters.indexOf(searchTerm1);
if (i != -1)
{
SelectedFilters.splice(i, 1);
}
I have also tried running to through for loop, to iterate on all items, but again search failed as its not able to match 'size' OR 'color'
What I am looking: if searchterm1 is used, the resulted output will be like:
["[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
and in case of searchterm2 is used the resulted output should be:
["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]","[type:14:14]","[type:14:14]"];
It would be great if anyone can solve this puzzle, I am also trying to find a solution in the meantime.
Your attempt didn't work because .indexOf() on an Array looks for an exact match.
Since according to your question and comment you need to mutate the original Array, you should loop over the array and test each string individually and then call .splice() every time you find one that needs to be removed.
var SelectedFilters = ["[size:12:12]","[size:12:12]","[size:13:13]","[size:14:14]", "[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
var searchTerm1 = 'size'
var searchTerm2 = 'color'
for (var i = SelectedFilters.length-1; i > -1; i--) {
if (SelectedFilters[i].startsWith(searchTerm1, 1)) {
SelectedFilters.splice(i, 1)
}
}
document.querySelector("pre").textContent =
JSON.stringify(SelectedFilters, null, 2)
<pre></pre>
The loop used above goes in reverse. This is important since every time we do a .splice(), the array gets reindexed, so if we went forward, we would end up skipping over adjacent items to be removed.
The .startsWith() method checks if the string starts with the given search term. I passed the second parameter a value of 1 so that it starts searching on the second character.
You can use filter method of array
var searchTerm = "size";
SelectedFilters = SelectedFilters.filter(function(val){
return val.indexOf( searchTerm ) == -1;
});
You can do it with Array#filter,
var searchTerm1 = 'size';
var result = SelectedFilters.filter(v => !v.includes(searchTerm1));
console.log(result); //["[color:14:14]","[color:14:14]","[type:14:14]","[type:14:14]"];
If you want to alter the original array then do,
var SelectedFilters = ["[size:12:12]", "[size:12:12]", "[size:13:13]", "[size:14:14]", "[color:14:14]", "[color:14:14]", "[type:14:14]", "[type:14:14]"];
var searchTerm1 = 'size',cnt = 0, len = SelectedFilters.length - 1;
while (cnt <= len) {
if (SelectedFilters[len - cnt].includes(searchTerm1)) SelectedFilters.splice(len - cnt, 1);
cnt++;
}
console.log(SelectedFilters);
DEMO

Categories

Resources