Spliting name and pushing to array - javascript

I have an array like this:
var abc = [
"Ken Robert Smith",
"Daniel Johnson"
]
How to split words in this array and push to new one that have first name(s) and surname separately? Any number of first names should be in first column and if there is only a surname it should go to 2nd column.
Im learning JavaScript. I tried some for loops and split() but unsuccessfully.

Adding some sample code would be useful, but in rough terms, you're going to want to do the following.
Iterate over the array. For each element in the array, split it by whitespace (.split()), then push the first element of your split element into your first name array, and the last element (which you can access at index -1) to the last name array.
I'll leave the actual code as an exercise to the student.

I recommend using a Set to store the names, assuming you don't want duplicates.
var abc = [ "Ken Robert Smith", "Daniel Johnson", "Ken Johnson" ];
const result = abc.reduce( ( result, name ) => {
const names = name.split( /\s+/g );
const surname = names.pop( );
result.surnames.add( surname );
names.forEach( name => result.firstNames.add( name ) );
return result;
}, {firstNames: new Set, surnames: new Set} );
console.log( result.firstNames ); // Set(3) {"Ken", "Robert", "Daniel"}
console.log( result.surnames ); // Set(2) {"Smith", "Johnson"}

So, only the last word is the last name, and the rest are the "first name".
I would split the name by space into an array, pop off the last element (last name), and then join the remaining elements to make the first name. Like this:
var abc = [
"Ken Robert Smith",
"Daniel Johnson"
];
var out = abc.map(function (el) {
var b = el.split(" ");
var ln = b.pop();
return [b.join(" "), ln];
});
console.log(out);

Related

Concatenate elements of an array Javascript

I have a list of hrefs with product data:name and it's id. First of all i removed prod Id that i'll use as separate variable.
After this, the remained part of href should be used as the product name.
var prodHref = document.querySelectorAll('.widget-products-list-item-label');
var allHref = [];
for(var i=0;i<prodHref.length;i++){
allHref.push(prodHref[i].href.split('/')[5])
}
var prodName = [];
for(var i=0;i<allHref .length;i++){
prodName.push(allHref [i].slice(0, -1))
}
var prodNameNew=[];
for(var i=0;i<prodName .length;i++){
prodNameNew.push(prodName[i].slice(0, -1))
}
So, the final result is on the attached screen. N
How i have concatenate all the elements of each array in order to get new arrays in the following format: Nokia G20 4 64 Albastru, Motorola G60 gri etc
Thank You
You want to capitalize the items of the inner arrays and then join them by space.
One way to do it is:
let result = arr.map(a => a.map(capitalize))
.map(a => a.join(" "))
where capitalize should be a function that takes a string and returns a string with first letter in upper case if possible.
You can find this in answers for the more specific SO question:
How do I make the first letter of a string uppercase in JavaScript?
Instead of 3 separate loops, we can get the substring based on single iteration only using Array.map() along with String.slice().
const prodHref = [{
href: "https://abc/def/ghi/alpha/mno"
}, {
href: "https://abc1/def1/ghi1/beta/mno1"
}, {
href: "https://abc2/def2/ghi2/gamma/mno2"
}, {
href: "https://abc3/def3/ghi3/omicron/mno3"
}];
const allHref = prodHref.map((obj) => obj.href.split('/')[5].slice(0, -2));
console.log(allHref);
Now you can use Array.join() method to join the result array.
const allHref = ["alp", "be", "gam", "omicr"];
console.log(allHref.join(" "));

Removing nickname from localStorage string

I'm trying to check localStorage for a nickname and if it includes the nickname remove it from the localStorage.
window.removeNickname = (n) => {
const names = localStorage['nicknames'].split(','); // Output = ["NAME 1", "NAME 2", "NAME 3"]
if (names.includes(n)) {
// HOW CAN I REMOVE THE NAME FROM THE LOCALSTORAGE HERE AND REPLACE THE LOCALSTORAGE NICKNAMES.
}
};
removeNickname('NAME 2');
You can try to remove the item from the array with split and set the new array as your nicknames.
Splice removes the items from array starting from the index that you mentioned in the first argument and removes as many elements as you set in the second argument.
window.removeNickname = (n) => {
const names = localStorage['nicknames'].split(','); // Output = ["NAME 1", "NAME 2", "NAME 3"]
if (names.includes(n)) {
localStorage.setItem(nicknames, names.splice(names.indexOf(n), 1));
}
};
This is a great use case for localDataStorage, a utility I authored. With localDataStorage you can create and manipulate Array Keys and store the value in localStorage. Some examples:
Create and initialize an Array Key in localStorage called nicknames with 3 element values:
> lds.push( 'nicknames', 'Mac', 'Bill', 'Will' );
Query the Array Key for a certain element:
> lds.contains( 'nicknames', 'Bill' );
true
Remove an element from the Array Key (specifying a value literal):
> lds.pull( 'nicknames', 'Bill' );
Get the updated key value:
> let newKey = lds.get( 'nicknames' );
['Mac', 'Will']
So your application might go something like this:
const removeNickname = (n) => {
lds.pull( 'nicknames', n );
return lds.get( 'nicknames' );
};
const addNickname = (n) => {
lds.push( 'nicknames', n ); // appends to array
return lds.get( 'nicknames' );
};
updatedNicknamesArray = removeNickname( 'Tom' );
updatedNicknamesArray = addNickname( 'Tim' );

How to search for the position of each word present in a string , inside the an array of words

What I want this code to do is:
search for the position of all the words present in the sentence "some warriors know when they are defeated,
whether some of them are too stubborn to accept it and they
are the one who die " inside the array_of_words
NOTE: I simply mean to search for the position of all the words present in array split_Sentence inside the array array_of_words.
I have given an example in the code below in blue color after //.
<html>
<body>
<script>
const Sentence= "some warriors know when they are defeated,
whether some of them are too stubborn to accept it and they
are the one who die "
const split_Sentence = Sentence.split(" ")
var array_of_words = ["some", "warriors", "know", "they",
"defeated", "whether", "too", "stubborn", "one", "die"]
var arrayLength=split_Sentence.length
//for example a function that searches for the position of the word "some" from the first array i.e. split_Sentence in the second array i.e. array_of_words
</script>
</body>
</html>
You can loop through the first array and in each iteration you can find the index of the current word from the second array using Array.prototype.indexOf():
split_Sentence.forEach(function(w){
console.log(array_of_words.indexOf(w));
});
Demo:
const Sentence= `some warriors know when they are defeated,
whether some of them are too stubborn to accept it and they
are the one who die `;
const split_Sentence = Sentence.split(" ");
var array_of_words = ["some", "warriors", "know", "they",
"defeated", "whether", "too", "stubborn", "one", "die"];
var arrayLength=split_Sentence.length;
//for example a function that searches for the position of the word "some" from the first array i.e. split_Sentence in the second array i.e. array_of_words
split_Sentence.forEach(function(w){
console.log(array_of_words.indexOf(w));
});
You can use sentence_split.indexOf for each str in array_of_words
<html>
<body>
<script>
const sentence= "some warriors know when they are defeated, whether some of them are too stubborn to accept it and they are the one who die "
const split_sentence = sentence.split(" ")
var array_of_words = ["some", "warriors", "know", "they", "defeated", "whether", "too", "stubborn", "one", "die"]
split_sentence.forEach(function(w){
console.log(w, " index ", array_of_words.indexOf(w));
});
</script>
</body>
</html>
JSFiddle:
/*
What i want this code to do is:
search for
the position of all the words present in the sentence "some warriors know when they are defeated, whether some of them are too stubborn to accept it and they are the one who die "
inside the array_of_words
NOTE: I simply mean to search
for the position of all the words present in array array_from_sentence inside the array array_of_words.
I have given an example in the code below in blue colour after //.
*/
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
/*
( method ) Array < string[] > .shift(): string[]
Removes the first element from an array and returns it.If the array is empty, undefined is returned and the array is not modified.
method ) Array < string > .filter( predicate: ( value: string, index: number, array: string[] ) => unknown, thisArg ? : any ): string[]( +1 overload )
Returns the elements of an array that meet the condition specified in a callback
function.
//------------------------------------------------------------------------------------------
#param predicate— A
function that accepts up to three arguments.The filter method calls the predicate
function one time
for each element in the array.
#param thisArg— An object to which the this keyword can refer in the predicate
function.If thisArg is omitted, undefined is used as the this value.
*/
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
const sentence =
'some warriors know when they are defeated whether some of them are too stubborn to accept it and they are the one who die';
const array_from_sentence = sentence.split(' ');
console.log('array_from_sentence: ', array_from_sentence);
/*
array_from_sentence: ['some', 'warriors', 'know','when', 'they', 'are',
'defeated', 'whether', 'some','of', 'them', 'are',
'too', 'stubborn', 'to','accept', 'it', 'and',
'they', 'are', 'the','one', 'who', 'die'];
*/
let array_of_words = [
'some',
'warriors',
'know',
'they',
'defeated',
'whether',
'too',
'stubborn',
'one',
'die',
];
//for example a function that searches for the position of the word "some" from the first array i.e. array_from_sentence in the array-of-words i.e. array_of_words
let ArrOfSentenceAndWords = [array_from_sentence, array_of_words];
let intersectionOfArrays = ArrOfSentenceAndWords.shift().filter(function (v) {
return ArrOfSentenceAndWords.every(function (a) {
return a.indexOf(v) !== -1;
});
});
console.log('intersectionOfArrays: ', intersectionOfArrays);
/*
intersectionOfArrays: [
'some', 'warriors', 'know', 'they',
'defeated', 'whether', 'some', 'too',
'stubborn', 'they', 'one', 'die']
*/
function finder(word) {
if (intersectionOfArrays.includes(word)) {
return `The word '${word}' was found at position ${array_of_words.indexOf(
word
)} of the array "array_of_words"`;
} else {
return `the word did not exist in the array_of_words`;
}
}
finder('some');
console.log(finder('some'));

How to generate permanent React keys for same string value in array?

I have a textbox where a user enters text. A search for specific keywords is then performed and the string is split at these keywords.
A first input may look like E.g.
[
0: "this is "
1: "word"
2: " a form field value with another "
3: "word"
]
A change then might be made to remove the first repeated word:
[
0: "this is "
1: " a form field value with another "
2: "word"
]
How can I create a persistent key for each array item? I need the second word value to have the same React key as when it is first generated regardless of array position. It is a separate component instance regardless of the same value. I have an issue right now where deleting one of the split words will delete both due to the keys changing after the first word is deleted.
Best practices say not to use the array index, but I'm unsure in this situation how else to generate a unique key.
This is a rough solution, but you can think of as a dictionary program.
class SomeComponent {
constructor() {
this.state = {
words: ["this is ", "word", " a form field value with another ", "word"]
};
this.wordMap = this.state.words.reduce((m, x, index) => {
m[index] = x;
return m;
}, {});
}
cleanWord() {
let unique = new Set();
for (let key in this.wordMap) {
if (unique.has(this.wordMap[key])) {
this.wordMap[key] = null; //duplicate
} else {
unique.add(this.wordMap[key]);
}
}
}
onDelete(index) {
this.wordMap[index] = null;
}
}
const dict = new SomeComponent();
dict.cleanWord();
console.log(dict.wordMap);
dict.onDelete(1);
console.log(dict.wordMap);
.as-console-row {color: blue!important}
You can use value as key, and keep the indexes as values
[
"this is ": [0]
"word": [1,3]
" a form field value with another ":[2]
]
And then when you remove one index it will look like
[
"this is ": [0]
"word": [3]
" a form field value with another ":[2]
]
You can use reduce to produce such format from your splitted string
let str = ["this is ", "word", " a form field value with another ", "word"]
let mapperObj = str.reduce((op, inp, index) => {
op[inp] = op[inp] || []
op[inp].push(index)
return op
}, {})
console.log(mapperObj)
You can use anything as the key, to the best of my knowledge, but you want them to be unique for each item.
I'd recommend base64'ing your item using btoa(JSON.stringify(object)) or creating a unique key like mentioned above by appending index to value, ${index}${value}
You can use index as key if you can mark deleted values as null. This value can be rendered without additional filtering.

Create an associative array after .split ()

I take the example from the developer.mozilla.org official documentation so you can answer it more easily:
var names = "Harry Trump; Fred Barney; Helen Rigby; Bill Abel; Chris Hand";
var re = / \ s *; \ s * /;
var nameList = names.split (re);
This regular expression produces an array formed by the various elements divided by the character ;.
My problem is this: I would like to associate with the array that is out of the element from which it was extracted, that is, ;.
Basically the goal is to get something like this:
[
{
";": ["Harry Trump"]
},
{
";": ["Fred Barney"]
}
...
]
instead of
[ "Harry Trump", "Fred Barney" , ... ]
Would you like to tie them up?
Here you go with the solution https://jsfiddle.net/fq3238ku/1/
var names = "Harry Trump, Fred Barney, Helen Rigby, Bill Abel, Chris Hand";
var splitName = names.split(',');
var data = [];
for(var i in splitName){
data[i] = {";" : [splitName[i]]};
}
console.log(data);
If your separator is variable you can do this way
let names = "Harry Trump, Fred Barney, Helen Rigby, Bill Abel, Chris Hand"
let re = /\s*(,)\s*/
let res = names.split(re).map(
(currentValue, index, array) => {
if (index%2!=0) {
return {
[currentValue]: (array[index-1] )
}
}
}
)
.filter((n)=>n)
console.log(res)
What you want to achieve is simply not possible. Once you have a value under key ; then assigning another value will simply overwrite the previous one.

Categories