I have an array
var hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
I understand that to look for a specified matching value I'd have to use this
if (hashtags.indexOf("#hr") > -1)
// output value
But how do I output ALL the matching values that match the condition?
You can use Array#filter and equality comparison to get all the occurrences of your word in the given array.
var hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
var result = hashtags.filter( word => word === '#hr');
console.log(result);
You can use Array#filter and check inside the condition. Also instead of indefOf you can use Array#includes function.
const hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
const filteredHashtags = hashtags.filter(item => item.includes('#hr'));
console.log(filteredHashtags);
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
Related
For example:
str = "A=sample_text1; B=sample_text2; C=sample_text3;";
How can I get the text after "A=", which is "sample_text1" out ? (the length of sample_text1 can be very long, so str.substring won't work here)
Looks like your string has a structure where there are multiple fields where each field is represented as:
[KEY]=[VALUE];
You can use common string and array methods like split and map to extract what you need. In this case looks like you want the value of the first field:
const str = 'A=sample_text1; B=sample_text2; C=sample_text3;';
const result = str.split(';').map(s => s.split('=').pop().trim()).shift();
console.log(result); //=> 'sample_text1'
https://regexr.com is very useful for creating and testing regex.
const match = "A=sample_text1; B=sample_text2; C=sample_text3;".match(/A=([^;]*)/);
let value = match !== null ? match[1] : undefined;
Would allow you to get the value of A in this case
You could use a regular expression to capture every group surrounded by a = and a ;:
const str = "A=sample_text1; B=sample_text2; C=sample_text3;";
const regexp = "=(.*?);";
const values = [...str.matchAll(regexp)];
const aValue = values[0][1];
console.log(aValue);
It might be an overkill, but to easily access to all the keys / values, you could use Object.fromEntries:
let str = "A=sample_text1; B=sample_text2; C=sample_text3;";
let values = Object.fromEntries(
str
// Split all the pairs
.split(";")
// Remove the last empty element
.slice(0,-1)
// map to a [key, value] array to pass to Object.fromEntries
.map(i => i.split("=").map(j => j.trim())));
// get a value using a key
console.log(values["A"]) // sample_text1
// check if a key is present
console.log("C" in values) // true
console.log("D" in values) // false
It looks more longer than it is due the comments and the console logs, it can fit in one line.
Notice that this is assume of course that neither the character = or ; can be part of the key or the value.
I have a string var whose value is (1,2)(3,4) and I'd like to extract an array [[1,2],[3,4]] from it. The solution I have is to use str.match but I haven't figured out how to extract the array.
I have tried:
> '(1,2)(3,4)'.match(/([\d]+),([\d])*/)
[ '3,2', '3', '2', index: 1, input: '(3,2)(4,5)', groups: undefined ]
The result is not what I want. So what should I do with the regex for that?
You need to use /(\d+),(\d+)/g or - to only get those inside parentheses - /\((\d+),(\d+)\)/g and get the results using RegExp#exec in a loop:
var s = '(1,2)(3,4)', m, results=[];
var rx = /(\d+),(\d+)/g;
while(m=rx.exec(s)) {
results.push([m[1], m[2]])
}
console.log(results);
Or, with matchAll if you target the latest JS environments:
const s = '(1,2)(3,4)', rx = /(\d+),(\d+)/g;
const results = [...s.matchAll(rx)];
console.log(Array.from(results, x => [x[1],x[2]]))
There's the other way around, without using RegExp, just in case:
const src = '(1,2)(3,4)',
result = src
.slice(1,-1)
.split(')(')
.map(s => s.split(','))
console.log(result)
.as-console-wrapper{min-height:100%;}
I have two arrays and the idea is to find text in first array and replace itwith the value of second array ( Same index ).
Example
Text to search & replace: Visina
var array1 = ['Visina','Tezina'];
var array2 = ['Height','Weight'];
So the script should search for "Visina" in first array, find the index and replace with the value from second array with same index.
Also, it needs to toggle.
Well, you simply should use Array.indexOf() method:
var array1 = ['Visina', 'Tezina'];
var array2 = ['Height', 'Weight'];
function swap(str) {
const index = array1.indexOf(str);
if (index !== -1) {
array1[index] = array2[index];
array2[index] = str;
}
}
swap('Visina');
console.log(array1);
console.log(array2);
Trying to check if 2 strings have matching word return true.
let 1st_string = chin, kore, span;
let 2nd_string = chin eng kore zulu
1st_string.split(',').indexOf(2nd_string) > -1
I tried above code but always returns false. I need to return true as 2_nd string contains 2 matching words from 1st_string.
Solved the names and values of the variables you can do the following
let first_string = 'chin, kore, span';
let second_string = 'chin eng kore zulu';
const array1 = first_string.split(',').map(string => string.trim());
const array2 = second_string.split(' ');
function exist(list1, list2) {
for (const element of list1) {
if (list2.includes(element)) {
return true;
}
}
return false;
}
const result = exist(array1, array2);
console.log(result);
1st_string is not a valid variable name
split the first string and use Array.some() to see if the second string has any of the words in the resulting array :
let string_1 = 'chin, kore, span';
let string_2 = 'chin eng kore zulu';
const check = (str1, str2) => {
return str1.split(',').some(word => str2.includes(word));
}
console.log(check(string_1, string_2))
I think your second string will also contain a comma in between the words if yes then it is easy to achieve.
you can split the string 1 and 2 with a comma as delimiter like this
let firstString = 1st_string.split(',');
let secondString = 2nd_string.split(',');
after doing you will get the firstString and secondString variable as array then you can iterate the first array and check for duplicate using includes methods
for (let i in firstString) {
if(secondString.includes(firstString[i])){
//you can do whatever you want after finding duplicate here;
}
}
I have an array of strings.
I want to search in that array for and string that contains a specific string.
If it's found, return that string WITHOUT the bit of the string we looked for.
So, the array has three words. "Strawbery", "Lime", "Word:Word Word"
I want to search in that array and find the full string that has "Word:" in it and return "Word Word"
So far I've tried several different solutions to no avail. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes looks promising, but I'm lost. Any suggestions?
Here's what I've been trying so far:
var arrayName = ['Strawberry', 'Lime', 'Word: Word Word']
function arrayContains('Word:', arrayName) {
return (arrayName.indexOf('Word:') > -1);
}
You can use find to search the array. And use replace to remove the word.
This code will return the value of the first element only.
let arr = ["Strawbery", "Lime", "Word:Word Word"];
let search = "Word:";
let result = (arr.find(e => e.includes(search)) || "").replace(search, '');
console.log(result);
If there are multiple search results, you can use filter and map
let arr = ["Strawbery", "Word:Lime", "Word:Word Word"];
let search = "Word:";
let result = arr.filter(e => e.includes(search)).map(e => e.replace(search, ''));
console.log( result );
Use .map:
words_array = ["Strawbery", "Lime", "Word:Word Word"]
function get_word(words_array, search_word) {
res = '';
words_array.map(function(word) {
if(word.includes(search_word)) {
res = word.replace(search_word, '')
}
})
return(res)
}
Usage:
res = get_word(words_array, 'Word:')
alert(res) // returns "Word Word"