I have a paragraph stored in a variable named story.
story = story text;
(example).
The first step in the project is to separate each word in the story variable and store it in an array named storyWords.
Easy enough, check.
Now it wants us to iterate through storyWords, filter out unnecessaryWords and store the new array in a variable named betterWords.
unnecessaryWords = ['extremely', 'literally', 'actually'];
Here is my code:
const betterWords = storyWords.filter(word => {
if(word !== unnecessaryWords)
return word;
});
What leads me to believe that this should work is based on this code:
const betterWords = storyWords.filter(word => {
if(word !== 'extremely')
if(word !== 'literally')
if(word !== 'actually')
return word;
})
What am I not understanding here?
If you want to exclude the entry as long as it matches any of the unnecessary words that is an array:
const unnecessaryWords = ['extremely', 'literally', 'actually'];
...then you can simply return !unnecessaryWords.includes(word), which means "if word is not included in the array of unnecessaryWords, we want to keep it":
const betterWords = storyWords.filter(word => !unnecessaryWords.includes(word));
Array.prototype.includes will return true when word matches any of the array members in unnecessaryWords.
Proof-of-concept:
const unnecessaryWords = ['extremely', 'literally', 'actually'];
const storyWords = ['Lorem', 'ipsum', 'extremely', 'dolor', 'sit', 'actually', 'amet'];
const betterWords = storyWords.filter(word => !unnecessaryWords.includes(word));
console.log(betterWords);
The following uses a regular expression and String#matchAll to match word character sequences following a word boundary. Array#filter is then used to filter out the unnecessary words.
const unnecessaryWords = ['extremely', 'literally', 'actually']
function betterWords(text) {
const words = [...text.matchAll(/\b\w+/gu)].flat()
return words.filter((w) => !unnecessaryWords.includes(w))
}
const text = 'literally the story text'
console.log(betterWords(text))
You could try two approaches. Using a Array.forEach() and Array.filter() like i demonstrated below.
// Just for Illustration, let's initialize a list representing storyWords
var storyWords = ['story','extremely', 'global','actually', 'javascript','c-sharp','literally'];
var unnecessaryWords = ['extremely', 'literally', 'actually'];
//First using simple loop
var betterWordsLooped = [];
storyWords.forEach((word)=>
{
if(!unnecessaryWords.includes(word))
{
betterWordsLooped.push(word);
}
});
console.log(betterWordsLooped);
//Secondly Using Filter
var betterWordsFiltered = storyWords.filter((word)=> !unnecessaryWords.includes(word));
console.log(betterWordsFiltered);
On this code:
!unnecessaryWords.includes(word))
we want to check if the value of variable word matches any of the items contained in the string array unnecessaryWords. Remember the pattern for using Array.propotype.includes() is someArray.includes(someVar) where someArray is a [] and someVar is a string variable whose value you want to match within someArray.
Related
I have this array
(2) ['beginning=beginner', 'leaves=leave']
and this string
its beginner in the sounds leave
which i have converted to an array
var words = text.split(' ');
i want to replace beginner with beginning and leave with leaves it can be any dynamic words but for now it has only two elements i can replace it within for loop. Is it possible with map method.
this.words.map((words, i) => console.log(words));
Note: Only first instance should get replaced.
Any Solution Thanks
does this correct with your question ?
const arrString = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let string = "its beginner in the sounds leave";
arrString.forEach((mapString) => {
const stringArr = mapString.split("=");
string = string.replace(stringArr[1], stringArr[0]);
});
console.log("string", string);
// "its beginning in the sound leaves"
You can do it in without a nested loop too if you compromise with space.
Here is a solution which creates a mapping object for replacement values and uses array methods like map(),forEach(),join() and string method like split()
const arrString = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let string1 = "its beginner in the sounds leave beginner";
const replaceObj = {};
const arrBreaks = arrString.forEach(x => {
let els = x.split("=");
replaceObj[els[1]] = els[0]; });
const ans = string1.split(' ').map((x) => {
if(x in replaceObj) { let val = replaceObj[x]; delete val; return val; }
return x;
}).join(' ');
console.log(ans);
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 got a String array, where I just need the first argument. The rest needs to be a string again. As an example, i use discord.js, and I work on a /kick command, so the usermention will be argument 1 and the rest will be the reason. But How could the array "Arguments" create a whole string without using the very first index? At the moment I just got this:
//The given arguments in the command get separated
var Arguments = message.content.split(" ");
//testing purpose, if the first index really is the mentioned user
message.channel.send("Username: " + Arguments[1]);
//joining the reasons together to a whole string
var reason = Arguments.join(/*This is the part where I don't know how to tell the array to ignore the first index*/);
Try assigning arguments to an array in the beginning:
var args = message.content.split(" ");
then before joining them you can remove the first element from the args:
args.shift();
You can use ES6 spread syntax:
const Arguments = ['Apple', 'Banana', 'Peach', 'Pear'];
const [first, ...remaining] = Arguments;
console.log(first) // Apple
const joinedRemaining = remaining.join(', ');
console.log(joinedRemaining); // Banana, Peach, Pear
Notice that in:
const [first, ...remaining] = Arguments;
first is the first value and remaining is the array with all the values, except the first
Use shift and join to do the trick
var a=["fd","fdd","fsdsd"]
console.log(a.shift()) //first element
console.log(a.join(",")); //rest in a string form
You can use slice
let str = "hello world how are you";
let splitStr = str.split(' ');
let arg = splitStr[0];
let rest = splitStr.slice(1).join(' ')
console.log(arg,'\n',rest)
Use desctructuring and the spread syntax to get the tail of the array:
const arguments = ['jack', 'john', 'sylvia', 'eddy'];
const [_, ...rest] = arguments;
const argString = rest.join(' ');
console.log(argString);
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"
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));