I have an array of strings. A user typed “ztaf”. How can I use JavaScript to find which of the letters the user typed match somewhere in the array? The answer should be “taf”.
var array = [ "tofu", "fish", "meat" ];
var user_type = "ztaf";
var found = ""; // It should be "taf".
I have tried it, but it keeps saying there is no match.
You can achieve this by using String.split() along with the Array.filter(), Array.join() and String.includes() methods.
Live Demo :
var array = ["tofu","fish","meat"];
var user_type = "ztaf";
var found = user_type.split('').filter(char => array.join().includes(char));
console.log(found.join(''));
Related
I need to compare two arrays for PARTIAL / SUBSTRING matches. If these are found, I want the matching items removed from the originalArray or create a new array with all those items that did not have a partial match,
var originalArray = ['www.google.com/opq', 'www.yelp.com/abc', 'www.yahoo.com/klm', 'www.bing.com/xyz', 'www.google.com/124'];
var itemsToBeRemoved = ['google.com', 'yahoo.com'];
// DESIRED ARRAY: An array with items that did not have a partial match. For example:
var cleanArray = ['www.yelp.com/abc', 'www.bing.com/xyz']
It work when its a FULL / EXACT match.
But it is NOT what I need.
function cleanFullMatch(){
// Your main array
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
Logger.log(originalArray);
// This array contains strings that needs to be removed from main array
var itemsToBeRemoved = ['www.google.com/rugby', 'www.yahoo.com/tennis', 'www.google.com/football'];
var cleanObj = {};
itemsToBeRemoved.forEach( e => cleanObj[e] = true);
itemsToBeRemoved.forEach( e => itemsToBeRemoved[e]= true);
var cleanArray = originalArray.filter(function(val){ return !cleanObj [val] })
Logger.log(cleanArray);
}
You can use JavaScript RegExp to create regular expression and array.filter(function) to remove elements that does not match the regex.
Sample Code:
function cleanFullMatch(){
// Your main array
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
Logger.log(originalArray);
// This array contains strings that needs to be removed from main array
var itemsToBeRemoved = ['google.com', 'yahoo.com', 'google.com'];
// loop through itemsToBeRemove
itemsToBeRemoved.forEach(function(rgx){
// convert each element of itemsToBeRemove to regular expression
var re = new RegExp(rgx);
// filter the array by removing the elements that match the regex
// test() method checks if the string matches the regex
originalArray = originalArray.filter( word => !re.test(word));
});
Logger.log(originalArray);
}
Sample Output:
filter out the elements of the originalArray so that none of the itemsToBeRemoved is present in any of the filtered elements.
There are many ways to check whether a substring is included in another string, as others said, like includes, indexOf and RegExp.
You could then iterate through all of these itemsToBeRemoved in different ways. You could, for example, use some:
function cleanFullMatch(){
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
var itemsToBeRemoved = ['google.com', 'yahoo.com'];
var cleanArray = originalArray.filter(element => !itemsToBeRemoved.some(item => element.includes(item)));
console.log(cleanArray);
}
Or, alternatively, every:
var cleanArray = originalArray.filter(element => itemsToBeRemoved.every(item => !element.includes(item)));
As you can see, the filtering process can be reduced to a single line.
I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for(i = o; i <array.length; i++)
var loopedArray = array[i].split("|")
loopedArray.push(array2);
}
I have tried several other things but would take me awhile to put them all down.
You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);
Your code snippet is close, but you've messed up your variables in the push statement.
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for (i = 0; i < array.length; i++) {
var loopedArray = array[i].split("|")
array2.push(loopedArray);
}
array2 = array2.flat();
console.log(array2);
However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
.split('$')
.flatMap(arrayI => arrayI.split('|'));
console.log(array2);
And lastly, split already supports multiple delimiters when using regex:
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);
console.log(array2);
You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')
It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]
If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
Console.WriteLine(singleString);
}
the output is:
XX
Y1234
ZT
QW4567
I have this type of list from javascript:
Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina
I used the following code to convert to my output
var array = columnsload.split(",");
var string = JSON.stringify(columnsload);
var nameArray = string.split(',');
The output is like this :
"Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina"
But I really need it like this :
["Amila","Asanka","Imaad","Kelum","Lakshan","Sagara","Thilina"]
Anyone know how to get output like this?
the split function is enough to convert the string into an array;
var names = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArr = names.split(",");
console.log( nameArr );
http://www.w3schools.com/jsref/jsref_split.asp
Just do var nameArray = columnsload.split(',');. You dont need to stringify the array and then split it again, just one .split would be enough.
var columnsload = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArray = columnsload.split(',');
console.log(nameArray);
If you need the whole thing to be string, you can run a JSON.stringify on the array after.
var columnsload = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArray = columnsload.split(',');
console.log(JSON.stringify(nameArray));
// outputs ["Amila","Asanka","Imaad","Kelum","Lakshan","Sagara","Thilina"]
// as one string.
How to split array values using 'angularjs.split' method? It is not working here:
var items =["Regular Servicing & Maintenance","Faults (Interior & Exterior)"];
console.log(items.split(',');
Well, your question is confusing on a number of levels. For one, there isn't an AngularJS function that I'm seeing in the documentation for split.
There's a JavaScript method called split(), but it's used to split a string into an array of substrings, per the linked documentation.
For another, you're already instantiating the items variable with an array of strings though, so you're not really going to get anything from that that you don't already have in the initial value.
Split Method
Now, if you had a string like the following example, you could split that by the commas and yield an array similar to what you've got in your question:
var str = "Apples, Bananas, Cherries";
var arr = str.split(', '); //Note the space as well
console.log(arr); //Yields ["Apples", "Bananas", "Cherries"]
Join Method
But if you're looking for the inverse and you're rather looking to join these into a comma-separated string, you might look at the join() JavaScript method that would look like the following (continued from above):
var result = arr.join(', '); //Note the space again
console.log(result); //Apples, Bananas, Cherries
IndexOf Method
To match the comment you left after I posted this though, if you're looking for the index value of the array that matches a given string, look at the indexOf() method, per the following (again, building from the above example):
var index = arr.indexOf('Bananas'); //Yields 1
var indexRes = arr[index]; //Yields 'Bananas'
If you're looking for something else, you're going to need to clarify the original question.
The below code represents JavaScript code
var items = ["Regular Servicing & Maintenance", "Faults (Interior & Exterior)"];
for (var i = 0; i < items.length; i++) {
console.log("Input:-" + items[i])
console.log("Output:-" + items[i].split('&'));
}
Input: -Regular Servicing & Maintenance
Output: -Regular Servicing, Maintenance
Input: -Faults(Interior & Exterior)
Output: -Faults(Interior, Exterior)
How to split array values using angularJs
$scope.items = [{
'item': 'Regular Servicing & Maintenance'
}, {
'item': 'Faults (Interior & Exterior)'
}]
$scope.array = [];
angular.forEach($scope.items, function(value, key) {
var splitLength = value.item.split('&').length;
for (var i = 0; i < splitLength; i++) {
$scope.array.push(value.item.split('&')[i]);
}
});
console.log($scope.array)
Hello I have a problem when you change the string in order to invoke an array in javascript, please help me,
I have had a array:
var fruit=['Apple','Banana','Orange'];
and I have data string from mysql:
example: var string = '0,2';
How to display an array of fruit which corresponds to the var string?
(Thanks for the help)
You have to split() the string to get an array of indexes instead of a string of indexes :
var indexes = '0,2'.split(','); //use the ',' char to split the string
Now, you have to pick fruits values corresponding to each index in the new indexes array create just before.
var res = []; //The new Array to contains new fruits
indexes.forEach(function(index) { //loop over fruit indexes we want
res.push(fruit[index]); //Add the juicy fruit :)
});
And you got the new array (res) with the juicy fruits :)
JSFiddle
EDIT:
Or, a shorter/nicer solution (thanks to Xotic750)
(the second argument of the map function specify the context (this))
var ids = '0,2';
var fruits = ['Apple','Banana','Orange'];
fruits = ids.split(',').map(function(index) {
return this[index];
}, fruits);
I don't know if it will work or not, but this is what I could think of:
var x = [];
for (var i = 0; i>=string.length; i+=2) {
x.push(fruit[string[i]]);
}
But use only even numbers as a comma is also present in the string.
You will need to split the string into an array by using the Split() method:
var myArray = string.split(",");
Then you can loop over the array and use its values as indexes in the fruit array. For example, the first fruit will be:
fruit[myArray[0]];