how to get values from an array in javascript? - javascript

let the array be
var array=
[
"me=Salman","Profession=student","class=highschool"
]
How do I extract the value of 'me' here?

Try this:
var result = '';
for(var values in array){
if(values.indexOf('me=') !== -1 ){
result = values.split('=')[1];
break;
}
}

You will need to search the array for your desired portion of the string, then remove what you searched for from the indicated string.
var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var findMatch = "me=";
var foundString = "Did not find a match for '"+findMatch+"'.";
var i = 0;
for (i = 0; i<array.length; i++) //search the array
{
if(array[i].indexOf(findMatch) != -1) // if a match is found
{
foundString = array[i]; //set current index to foundString
foundString = foundString.substring(findMatch.length, array[i].length); //remove 'me=' from found string
}
}

Try this:
var a = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var result = a.filter(function(e){return /me=/.test(e);})[0]; // Find element in array
result = result.length ? result.split('=').pop() : null; // Get value
Or function:
var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];
function getVal(arr, key){
var reg = new RegExp(key + '=');
var result = arr.filter(function(e){ return reg.test(e)})[0];
return result.length ? result.split('=').pop() : null;
}
console.log( getMe(array, 'me') );

Related

JavaScript 2D array, if input RegEx match col1 , return col2

I trying to set up a chatbot which when user input match some word, then will response accordingly.
this works
var input = "i love you";
if(/.*cute.*/.test(input)) { alert("Aw.... so sweet");}
if(/.*love.*/.test(input)) { alert("Love you too");}
//result "Love you too"
However, how can I put the data in an array and still make it works?
example:
var queryResponse = [ ["cute","Aw.... so sweet"],
["love","Love you too"] ];
How do I modify this line?
if(/.* (what should i insert here?) .*/.test(input)) { alert(So that the response appear here?);}
index of each keys and value should match
var keys=['cute','love'];
var values= ['so cute', 'i love you'];
for(var i = 0; i < keys.length ; i++){
let re = new RegExp(`.*${keys[i]}*.`);
if(re.test(input){
alert(values[i]);
break;
}
}
You can do like this:
var regexArray = [ ["cute","Aw.... so sweet"],["love","Love you too"] ]
for(var i = 0; i < regexArray.length ; i++){
let re = new RegExp(`.*${regexArray[i][0]}*.`);
if(re.test(input){
alert(regexArray[i][1]);
break;
}
}
const queryResponseMap = new Map([
["cute", "Aw.... so sweet"],
["love", "Love you too"]
]);
function getResponse(query) {
const iterator = queryResponseMap.entries();
let result = iterator.next();
while (!result.done) {
const [key, val] = result.value;
if (new RegExp(`.*${key}*.`).test(query)) {
return val;
}
result = iterator.next();
}
return null;
}
console.log(getResponse("Hi love"));
console.log(getResponse("You're cute"));

how to convert json values in comma separated string using javascript

I have following JSON string :
{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}
I want location_id as
3,2
Simple:
var data = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var result = data.map(function(val) {
return val.location_id;
}).join(',');
console.log(result)
I assume you wanted a string, hence the .join(','), if you want an array simply remove that part.
You could add brackets to the string, parse the string (JSON.parse) and map (Array#map) the property and the join (Array#join) the result.
var string = '{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}',
array = JSON.parse('[' + string + ']'),
result = array.map(function (a) { return a.location_id; }).join();
console.log(result);
obj=[{"name":"Marine Lines","location_id":3}, {"name":"Ghatkopar","location_id":2}]
var res = [];
for (var x in obj)
if (obj.hasOwnProperty(x))
res.push(obj[x].location_id);
console.log(res.join(","));
var json = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var locationIds = [];
for(var object in json){
locationIds.push(json[object].location_id);
}
console.log(locationIds.join(","));
You can also look into .reduce and create a string manually
var d = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var location_id_str = d.reduce(function(p, c) {
return p ? p + ',' + c.location_id : c.location_id
},'');
console.log(location_id_str)
try this
var obj = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var output = obj.map( function(item){
return item.location_id;
});
console.log( output.join(",") )
var arr = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var location_array = [];
for( var i = 0; i < arr.length; i++ )
{
location_array.push( arr[i].location_id );
}//for
var location_string = location_array.join(",");
console.log(location_string);
Note: You may need to use JSON.parse() if the arr is in string format initially.
You can use for..of loop
var arr = [{
"name": "Marine Lines",
"location_id": 3
}, {
"name": "Ghatkopar",
"location_id": 2
}];
var res = [];
for ({location_id} of arr) {res.push(location_id)};
console.log(res);

Count the number of unique occurrences in an array that contain a specific string with Javascript

Here is my javascript array:
arr = ['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots'];
With Javascript, how can I count the total number of all unique values in the array that contain the string “dots”. So, for the above array the answer would be 3 (blue-dots, orange-dots, and red-dots).
var count = 0,
arr1 = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf('dots') !== -1) {
if (arr1.indexOf(arr[i]) === -1) {
count++;
arr1.push(arr[i]);
}
}
}
you check if a certain element contains 'dots', and if it does, you check if it is already in arr1, if not increment count and add element to arr1.
One way is to store element as key of an object, then get the count of the keys:
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
console.log(Object.keys(arr.reduce(function(o, x) {
if (x.indexOf('dots') != -1) {
o[x] = true;
}
return o
}, {})).length)
Try this something like this:
// Create a custom function
function countDots(array) {
var count = 0;
// Get and store each value, so they are not repeated if present.
var uniq_array = [];
array.forEach(function(value) {
if(uniq_array.indexOf(value) == -1) {
uniq_array.push(value);
// Add one to count if 'dots' word is present.
if(value.indexOf('dots') != -1) {
count += 1;
}
}
});
return count;
}
// This will print '3' on console
console.log( countDots(['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots']) );
From this question, I got the getUnique function.
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
then you can add a function that counts ocurrences of a string inside an array of strings:
function getOcurrencesInStrings(targetString, arrayOfStrings){
var ocurrencesCount = 0;
for(var i = 0, arrayOfStrings.length; i++){
if(arrayOfStrings[i].indexOf(targetString) > -1){
ocurrencesCount++;
}
}
return ocurrencesCount;
}
then you just:
getOcurrencesInStrings('dots', initialArray.getUnique())
This will return the number you want.
It's not the smallest piece of code, but It's highly reusable.
var uniqueHolder = {};
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
arr.filter(function(item) {
return item.indexOf('dots') > -1;
})
.forEach(function(item) {
uniqueHolder[item] ? void(0) : uniqueHolder[item] = true;
});
console.log('Count: ' + Object.keys(uniqueHolder).length);
console.log('Values: ' + Object.keys(uniqueHolder));
Try this code,
arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
sample = [];
for (var i = 0; i < arr.length; i++) {
if ((arr[i].indexOf('dots') !== -1) && (sample.indexOf(arr[i]) === -1)){
sample.push(arr[i]);
}
}
alert(sample.length);
var arr = [ "blue-dots", "blue", "red-dots", "orange-dots", "blue-dots" ];
var fArr = []; // Empty array, which could replace arr after the filtering is done.
arr.forEach( function( v ) {
v.indexOf( "dots" ) > -1 && fArr.indexOf( v ) === -1 ? fArr.push( v ) : null;
// Filter if "dots" is in the string, and not already in the other array.
});
// Code for displaying result on page, not necessary to filter arr
document.querySelector( ".before" ).innerHTML = arr.join( ", " );
document.querySelector( ".after" ).innerHTML = fArr.join( ", " );
Before:
<pre class="before">
</pre>
After:
<pre class="after">
</pre>
To put this simply, it will loop through the array, and if dots is in the string, AND it doesn't already exist in fArr, it'll push it into fArr, otherwise it'll do nothing.
I'd separate the operations of string comparison and returning unique items, to make your code easier to test, read, and reuse.
var unique = function(a){
return a.length === 0 ? [] : [a[0]].concat(unique(a.filter(function(x){
return x !== a[0];
})));
};
var has = function(x){
return function(y){
return y.indexOf(x) !== -1;
};
};
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
var uniquedots = unique(arr.filter(has('dots')));
console.log(uniquedots);
console.log(uniquedots.length);

How to find the string that matches in array?

I would like to get the full string element from an array that matches multiple substrings in no particular order. If more than one match, an exception should be thrown.
var thisArray = [ '/something_else/', '/and_something_else/', '/and_something_else_here/'];
var thisMatch = [ 'some', 'and', 'here'];
var matchingElement = new RegExp(thisArray , thisMatch); // Not sure about this
What I want is for matchineElement to contain the string "and_something_else_here" after the regular expression has executed.
You could do something like this:
var thisArray = [ '/something_else/', '/and_something_else/', '/and_something_else_here/'];
var thisMatch = [ 'some', 'and', 'here'];
function matchElements(arr, arrMatch) {
var tmpArr;
arrMatch.forEach(function(el, i, a) {
tmpArr = arr.filter(function(str) {
return str.indexOf(el) !== -1;
});
});
if (tmpArr.length > 1) {
throw ("Hey, too many matches");
} else {
return tmpArr[0];
}
}
console.log(matchElements(thisArray, thisMatch));
JSFiddle: http://jsfiddle.net/Le53y7ee/
Explanation:
The function goes through every element in the array containing substrings and filters main array keeping only strings that match. After the loop is done the array should contain only string(s) that matched all required substrings.
A regexp that matches a string containing all of a set of substrings looks like:
^(?=.*?string1)(?=.*?string2)(?=.*?string3).*$
So you just need to convert your thisMatch array into such a regular expression.
var regexp = new RegExp('^' + thisMatch.map(function(x) {
return '(?=.*?' + x + ')';
}).join('') + '.*$');
Then you can find all the matches with:
var matchingElements = thisArray.filter(function(x) {
return regexp.test(x);
});
if (matchingElements.length != 1) {
throw new Error('Single match not found');
} else {
matchingElement = matchingElements[0];
}
DEMO
Try
var matchingElement = thisArray.filter(function(val, key) {
var value = val.split(/[^a-z]/).filter(String).join(" ");
// if `.test()` returns `true` three times at `value`
return new RegExp(this[0]).test(value)
&& new RegExp(this[1]).test(value)
&& new RegExp(this[2]).test(value)
? val
: null
}.bind(thisMatch))[0].replace(/\//g,"");)
var thisArray = [ '/something_else/', '/and_something_else/', '/and_something_else_here/'];
var thisMatch = [ 'some', 'and', 'here'];
var matchingElement = thisArray.filter(function(val, key) {
var value = val.split(/[^a-z]/).filter(String).join(" ");
// if `.test()` returns `true` three times at `value`
return new RegExp(this[0]).test(value)
&& new RegExp(this[1]).test(value)
&& new RegExp(this[2]).test(value)
? val
: null
}.bind(thisMatch))[0].replace(/\//g,"");
document.write(matchingElement)
Take those slashes off of both sides of your Strings in those Arrays. Then use the arrayMatch function below, and loop over your indexes to get the results of thisArray, like:
function arrayMatch(yourArray, wordMatchArray){
var ix = [], c = wordMatchArray.length;
for(var i=0,l=yourArray.length; i<l; i++){
var m = 0;
for(var n=0; n<c; n++){
if(yourArray[i].match(new RegExp(wordMatchArray[n])))m++;
if(c === m)ix.push(i);
}
}
if(!ix[0]){
return false;
}
return ix;
}
var indexes = arrayMatch(thisArray, thisMatch);
for(var i=0,l=indexes.length; i<l; i++){
var getMatch = thisArray[indexes[i]];
}

To loop within array of arrays

In my below code Im am not able to fetch data within array
var str = "Service1|USER_ID, Service1|PASSWORD"
var str_array = str.split(',');
console.log(str_array)
for(var i = 0; i < str_array.length; i++)
{
str_array[i] = str_array[i].split('|');
}
console.log(str_array)
This is the response from above code
/* [ [ 'Service1', 'USER_ID' ],
[ 'Service1', 'PASSWORD' ] ]*/
I want response to be in two different array like below
var array1 = ['Service1']
var array2 = ['USER_ID','PASSWORD']
Any help on this will be really helpful
Since you're on Node, you can do this:
var str = "Service1|USER_ID, Service1|PASSWORD";
var result = str.split(',').reduce(function(collected,splitByComma){
var splitData = splitByComma.split('|');
var key = splitData[0].replace(/\s+/gi,''); //Might want to improve this "trim"
var data = splitData[1];
if(!collected.hasOwnProperty(key)) collected[key] = [];
collected[key].push(data);
return collected;
},{});
console.log(JSON.stringify(result)); //{"Service1":["USER_ID","PASSWORD"]}
//result.Service1[0] == USER_ID
//result.Service1[1] == PASSWORD
It's not wise to place stuff in separate places. You could have them under an object key though. If service name is variable, then you could do:
var serviceName = "Service1";
result[serviceName][0] == USER_ID
result[serviceName][1] == PASSWORD
As I have understand your question, you will want an array associated with each service key, to be able to do
services.service1
and get ['username', 'password' ] ?
If so, here's a solution:
var str = "Service1|USER_ID, Service1|PASSWORD".replace(', ', ',').split(','), //[ 'Service1|USER_ID', 'Service1|PASSWORD' ]
out = {};
str.forEach(function(element){
var key, value;
element = element.split('|');
key = element[0].trim();
value = element[1].trim();
out[key] = out[key] || []; // ensures we can push the value into an array
out[key].push(value);
});
console.log(out); //{ Service1: [ 'USER_ID', 'PASSWORD' ] }
We can have a simple Regex solution
var res = "Service1|USER_ID, Service1|PASSWORD".split(/[\|,]/g);
var ar1 = [], ar2 = [];
res.forEach(function(em,i){
if(i%2==0) {
if(ar1.indexOf(em.trim())<0){
ar1.push(em.trim());
}
} else {
ar2.push(em.trim());
}
});
//ar1 and ar2 will contain expected results

Categories