Chaining array and string methods in javascript - javascript

I try to chain some array and string methods but it doesn't work. It'd be great if anyone could explain to me why a function such as this doesn't work:
const scream = text => text.split('').push('!').join('').toUpperCase()

You could use Array#concat to return an array with another value instead of Array#push, which returns the new length, but is not part of a fluent interface for a later joining (which needs an array).
const scream = text => text.split('').concat('!').join('').toUpperCase();
console.log(scream('hi'));

Push doesn't return the array. Here's an example that demonstrates what's happening with push, and shows another way to do it:
const scream = text => text.split('').push('!').join('').toUpperCase()
const test = ['a', 'b', 'c'];
const result = test.push('!')
console.log(result)
const newScream = text => [
...text,
'!'
].join('').toUpperCase()
newScream('hello')
console.log(newScream('hello'))

If you want to add 1 ! at the end:
const scream = text => text.split('').concat('!').join('').toUpperCase();
If you want to add it after each letter:
const scream = text => text.split('').map(e => e + '!').join('').toUpperCase();
The push don't return array, so join is not called on array in your case.

If you want to add character/string at the end of string use concat(<ch>) function. If you want to change case to upper then use toUpperCase() function.
Or
Simply you can use + operator to concat two strings and append ! to it.
var str = "Hello World";
var res = str.toUpperCase().concat("!");
var result = (str + '!').toUpperCase();
console.log(res);
console.log(result);

Related

How can I get a full string that contains a substring in Javascript?

For example:
I have a array
const tags = ['size-1', 'size-2', 'discount-xyz']
In this case to check if I have a substring with discount in it, I have converted the array to a string
const arrayToString = tags.toString();
The output:
const tagsArrayToString = size-1,size-2,discount-wyx;
And I check if with a IF statement like this:
if ( tagsArrayToString.indexOf("discount") !== -1 ) { doSomething }
So far so good. But how can I get the full String like "discount-xyz"?
I wouldn't convert the tags array to a string - you already have the strings nice and separated, and this would only make things harder.
Instead, you could filter the array:
const filteredTags = tags.filter(t => t.includes('discount'));
Or, if you know there's just one such string, you could use find to get it:
const relevantTag = tags.find(t => t.includes('discount'));
Find the index of the discount tag using findIndex method, in turn find the tag itself via the index of the array.
const index = tags.findIndex(t => t.indexOf('discount') !== -1);
const discountTag = tags[index];

How to split pipe separated string into array of object

I have pipe separated string (sshshhs , 1) | (ee23es , 1) , I want to split and make an array of object . Result must be like [ {name:sshshhs,value:1},{name:ee23es,value:2} ]. I am new to JavaScript could someone please help me .
Thanks
Check out this code snippet
let myString = "(sshshhs , 1) | (ee23es , 1)";
// extract only the elements
let stringList = myString .split(/\) \| \(|\(|\)/);
// remove first and last empty elements, due to regex
stringList = stringList.slice(1,-1);
//split each element into an object
let objList = stringList.map(s => {
const [name, value] = s.split(',').map(el => el.trim());
return { name, value };
})
In this way with one regex you get rid of pipe and parenthesis. Then with a map you extract the name and value from each element.
You have multiple ways to transform your string into an array of object
One of them could be to split multiple times and use reduce to make the object
"(sshshhs , 1) | (ee23es , 1)"
.split('|') // here we first split with the principal key
.map(e => {
return [e.replace(/\(|\)/g, '')] // we create an object of your values to reduce it
.reduce((result, token) => {
const [name, value] = token.split(',').map(e => e.trim()); // we get the key/values by splitting it (and trimming it by the same time)
return {name, value}; // we then return the finded name and value
}, {})
})
This is definitly not the most efficient way to do it, but it will help you understand the mechanics behind split and reduce and help you create your own solution

How to convert string in an array?

From http response I received an object like this:
{"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
The key is an array...Is there a way in typescript to convert the key
"[3, company1]"
in an array like this
[3, "company1"]
?
You can combine Object.keys with map and transform the string to array with split
let data = {"[3, company1]":["role_user"], "[4, company2]":["role_admin"] }
let keys = Object.keys(data)
.map(
el =>
el.replace('[', '')
.replace(']', '')
.split(',')
.map(el => el.trim())
.map(el => isNaN(parseFloat(el))
? el
: parseFloat(el))
)
console.log("Keys: ", keys)
Here is the fiddle:
https://jsfiddle.net/to38g6cb/1/
What do you want to convert the keys to?
if want to convert it to a normal array then the below should do.
const httpResponse = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
};
const convertedKeys = Object.keys(httpResponse).map(value => {
let keyArray = value.replace("[", "").replace("]", "").split(", ");
return [parseInt(keyArray[0]), keyArray[1]];
});
console.log(convertedKeys);
If the above is not what you wanted, please kindly rephrase your question again.
You can remove the first and last character using slice(1,-1) and split the string at /\s*,\s*/ (comma with optional spaces on either side).
Then convert the first part to a number and return the array
const input = {
"[3, company1]": ["role_user"],
"[4, company2]": ["role_admin"]
}
const output = Object.keys(input).map(k => {
const [n, comp] = k.slice(1,-1).split(/\s*,\s*/)
return [+n, comp]
})
console.log(JSON.stringify(output))
It would have been easier if the company1 part were already quoted, so that you could just use JSON.parse. In fact, let's just do that! Put quotes around the company1 part with search and replace.
let key = `[3, company1]`;
let obj = JSON.parse(key.replace(/[$A-Z_]\w*/gi, '"$&"'))
console.log(obj);
Note: I'm guessing at what characters might be valid and went with something that looks vaguely like a JavaScript identifier. [$A-Z_]\w* Obviously not commas and right square brackets, due to deserialization ambiguity.

How to check if a string contains one of the elements from an array in Javascript?

I have a string var str = "I like roses"; and an array containing var arr1 = ['roses','daisy','lily','petunia']
I want to check if my string contains one or more than one element of the array arr1.
Expected Output : str contains an element from arr1
How can I do that in javascript?
I know how to check all the elements in an array using .every.
var str = 'I will have a mango and a banana';
var arr = ['mango','banana'];
var isEvery = arr.every(item => str.includes(item));
console.log(isEvery);
Output: true
How can I do it for just one element?
Array.prototype.some has already been proposed by #Ele and will likely best suit your needs.
One can take the funky route and use a regex
const v = ['mango', 'banana']
const check = s => !!s.match(new RegExp(`(${v.join('|')})`))
console.log(check('me mango and banana'))//true
console.log(check('me mango'))//true
console.log(check('me nothing'))//false
Not an elegant solution but this should work. Im sure you can clean it up
const arrayCompare = () =>{
const str = "I like roses";
const arr1 = ['roses','daisy','lily','petunia']
const newArray = str.split(' ');
for(let element of newArray){
if(arr1.includes(element)){
return 'String contains element from arr1'
}
}
return false;
};

How to return ONLY the matched / filtered string in an array?

I'm creating a small application for connection to an API and append cards from magic the gathering JSON file onto an HTML webpage.
Those cards should be searchable and for that to happen I need to somehow create a filter()
I'm new and still in school at this subject.
I have pulled out only the card Names in the variable called "arr" and is trying to filter out / or match with a value from the search input field which is "strInput"
document.getElementById("searchButton").addEventListener("click", function(e){
const parentDiv = document.getElementById("cards");
if ( parentDiv.hasChildNodes() === true ) {
removeStuff();
} else {
filteredCards("https://api.magicthegathering.io/v1/cards");
}
}, false)
displayCards("https://api.magicthegathering.io/v1/cards");
function filteredCards(url) {
fetch(url)
.then((resp) => resp.json())
.then((data) => {
let myInput = document.getElementById("search").value;
let strInput = '"' + myInput + '"';
let arr = [];
for ( i in data.cards) {
let jsonValue = data.cards[i];
let name = jsonValue.name;
arr.push(name);
}
let result = strInput.match(arr);
console.log(result);
console.log(arr);
console.log(strInput);
});
};
console.log(arr); // returns NULL even thought the string matches.
There's two ways to do it simply that I could think of, .find() and .filter()
.find() is going to return you the first match, and as a string
.filter() is going to return you the all matches, and as an array
They both work with the same style of code, you're just changing the method name
arr.filter(item => item === strInput) | arr.find(item => item === strInput
Just as a little aside, there's a few things you could swap out to get those sweet sweet brownie points
let arr = [];
for ( i in data.cards) {
let jsonValue = data.cards[i];
let name = jsonValue.name;
arr.push(name);
}
Can instead be wrote using the map function
let arr = data.cards.map((card) => card.name);
.
Also, you don't need to do '"' + myInput + '"'; to make sure something is a string, which is what you might be trying to do there - you can just use myInput.toString() - of course your data might have the names include the quotes, but just in case this is a mistake I thought I'd point it out
The parameter passed to match method is not really a matcher but a string. The method expects a regex to be passed in.
Just build out a simple regex expression and then iterate over the data.cards and add it into the array if the condition passes. You can look at the filter available on the array object.
let myInput = document.getElementById("search").value;
let myInputRegex = new Regex(myInput, 'gi');
let arr = [];
const matchedTokens = data.cards.filter(card => {
return card.name.match(myInputRegex);
});
console.log(matchedTokens);
console.log(strInput);
You can make a method that uses array.Find() and pass in the arr and strInput. array.Find() will find the first match
getName: function (arr, strInput) {
var name = arr.find(n => n === strInput)
return name
}
Here's some more reading from the official mozzila docs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Thanks!
This was exactly what i was looking for :D
let myInput = document.getElementById("search").value;
let myInputRegex = new Regex(myInput, 'gi');
let arr = [];
const matchedTokens = data.cards.filter(card => {
return card.name.match(myInputRegex);
});
console.log(matchedTokens);
console.log(strInput);

Categories

Resources