Javascript array manipulation / splice(), slice() - arrays

Javascript beginner.
I apply the split() method to the string, and next apply the splice() array method to the words array, removing two words at array "index 3", "really" and "cool" Since the splice () method returns any deleted words to display these in an alert dialog.
But "index" is unhappy with the code.
the output from script is:
JpowerfulaScript is really cool language
I want the output "javascript is perfect language"
enter image description here

Complete solution here
function wrangleArray() {
var sentence = "JavaScript is really cool language";
document.getElementById('div1').innerHTML = "<p>"+ sentence + "</p>";
var words = sentence.split(" ");
words.splice(2, 2, "powerful");
document.getElementById('div2').innerHTML = '<p>'+ words.join(" ") + '</p>';
}

As far as I can see from your code, you have this line:
var words = sentence.split('');
Your mistake here as I see it is, you are not splitting by spaces (' ') but rather by empty strings.
As can be seen from this fiddle splitting by an empty string (the '' entry in your code), means splitting by every character (since after every character you technically do have an empty string).

Related

I would like to retrieve words with their number of characters

Like in the title. I would like to retrieve words with their number of characters with Ruby. I have searched a lot there are a lot of methods to select elements in an array. But is it possible to recover for example only the strings which contain 5 characters in my array?
Thank you in advance !
Sure, something like this could work
words_with_five_characters = words.select { |w| w.length == 5 }
I assume you already converted your title to an array of words, in which case the answer from #Ursus is perfect.
If that's of any help, you can also start from the string directly and use scan with a regular expression to identify 5 letter words:
title = 'this is my title and it has a lot of words including some longer than five characters'
title.scan(/\b\w{5}\b/)
=> ["title", "words"]

Perl remove spaces from array elements

I have an array which contains n number of elements. So there might be chances the each element could have spaces in the beginning or at the end. So I want to remove the space in one shot. Here is my code snippet which is working and which is not working (The one which not working is able to trim at the end but not from the front side of the element).
Not Working:
....
use Data::Dumper;
my #a = ("String1", " String2 ", "String3 ");
print Dumper(\#a);
#a = map{ (s/\s*$//)&&$_}#a;
print Dumper(\#a);
...
Working:
...
use Data::Dumper;
my #a = ("String1", " String2 ", "String3 ");
print Dumper(\#a);
my #b = trim_spaces(#a);
print Dumper(\#b);
sub trim_spaces
{
my #strings = #_;
s/\s+//g for #strings;
return #strings;
}
...
No idea whats the difference between these two.
If there is any better please share with me!!
Your "not working example" only removes spaces from one end of the string.
The expression s/^\s+|\s+$//g will remove spaces from both ends.
You can improve your code by using the /r flag to return a modified copy:
#a = map { s/^\s+|\s+$//gr } #a;
or, if you must:
#a = map { s/^\s+|\s+$//g; $_ } #a;
This block has two problems:
{ (s/\s*$//)&& $_ }
The trivial problem is that it's only removing trailing spaces, not leading, which you said you wanted to remove as well.
The more insidious problem is the misleading use of &&. If the regex in s/// doesn't find a match, it returns undef; on the left side of a &&, that means the right side is never executed, and the undef becomes the value of the whole block. Which means any string that the regex doesn't match will be removed and replaced with a undef in the result array returned by map, which is probably not what you want.
That won't actually happen with your regex as written, because every string matches \s*, and s/// still returns true even if it doesn't actually modify the string. But that's dependent on the regex and a bad assumption to make.
More generally, your approach mixes and matches two incompatible methods for modifying data: mutating in place (s///) versus creating a copy with some changes applied (map).
The map function is designed to create a new array whose elements are based in some way on an input array; ideally, it should not modify the original array in the process. But your code does – even if you weren't assigning the result of map back to #a, the s/// modifies the strings inside #a in place. In fact, you could remove the #a = from your code and get the same result. This is not considered good practice; map should be used for its return value, not its side effects.
If you want to modify the elements of an array in place, your for solution is actually the way to go. It makes it clear what you're doing and side effects are OK.
If you want to keep the original array around and make a new one with the changes applied, you should use the /r flag on the substitutions, which causes them to return the resulting string instead of modifying the original in place:
my #b = map { s/^\s+|\s+$//gr } #a;
That leaves #a alone and creates a new array #b with the trimmed strings.

How do I display strings from an array vertically stacked?

I am trying to take each string in my array and list them in a label one string per line. I tried using the joined method with /n to attempt to make it got to the next line but it just literally puts /n in between each string. I'm sorry if this happens to be a duplicate but unless I'm wording my question wrong I cant seem to find an answer. This is an example of what I'm looking for.
String[0]
String[1]
String[2]
and so on...
Try this:
let array = ["The", "quick", "brown", "fox"]
let string = array.joined(separator: "\n")
joined returns a new string by concatenating the elements of the sequence, adding the given separator (in this case, a line break) between each element in the array.
That will return this:
The
quick
brown
fox
...and set yourLabel.numberOfLines = 0
From Apple's documentation:
The default value for this numberOfLines is 1. To remove any maximum
limit, and use as many lines as needed, set the value of
numberOfLines to 0.
First make sure that the label can display multiple lines. If the UILabel is named lblText, then:
lblText.numberOfLines = 0
Then, simply use string interpolation to add in the line feeds:
lblText.text = "\(String[0])\n\(String[1])\n\(Stribng[2])"
The issue might be that you used "/n" instead of "\n" :)

Using variables with %w or %W - Ruby

I have a similar issue as this post:
How to use variable inside %w{}
but my issue is a bit different. I want to take a string variable and convert it to an array using %w or %W.
text = gets.chomp # get user text string
#e.g I enter "first in first out"
words = %w[#{text}] # convert text into array of strings
puts words.length
puts words
Console output
1
first in first out
Keeps the text as a block of string and doesn't split it into an array words ["first","in", "first", "out"]
words = text.split (" ") # This works fine
words = %w[#{gets.chomp}] # This doesn't work either
words = %w['#{gets.chomp}'] # This doesn't work either
words = %W["#{gets.chomp}"] # This doesn't work either
words = %w("#{gets.chomp}") # This doesn't work either
%w is not intended to do any splitting, it's a way of expressing that the following string in the source should be split. In essence it's just a short-hand notation.
In the case of %W the #{...} chunks are treated as a single token, any spaces contained within are considered an integral part.
The correct thing to do is this:
words = text.trim.split(/\s+/)
Doing things like %W[#{...}] is just as pointless as "#{...}". If you need something cast as a string, call .to_s. If you need something split call split.

Subscript out of range when trying to get last item of an Array

For example, I have a string A-456-BC-123;DEF-456;GHI-789. And I need to search for second part:DEF-456 with keyword 456. The potential problem here is that the first part A-456-BC-123 also has the keyword 456. Currently my logic is that, split the string first using ;, split each of it again using -, get the last item of this Array, search keyword 456. Another thing is that I don't want to do a full keyword match like DEF-456, I only want to use 456 as keyword to locate DEF-456, in other words, 456 should be the last segment of the string I want.
Here are my codes:
FirstSplit= split("A-456-BC-123;DEF-456;GHI-789",";")
For each code in FirstSplit
SecondSplit = split(FirstSplit,"-")
'get Array Count
Count = Ubound(SecondSplit)
'get the last item in Array
If SecondSplit(Count-1) = "456" Then
'doing something
End if
Next
Currently, an error will generate at SecondSplit(Count-1), saying that "Subscript out of range: '[number: -1]'"
Could someone tell me how to fix it?
The real problem is here:
SecondSplit = Split(FirstSplit, "-")
You should be splitting your element which you've stored in variable code from your For Each loop. By trying to split an array you should be getting a Type Mismatch error, but perhaps vbscript is forgiving enough to attempt and return a 0 element array back or something. Anyway:
SecondSplit = Split(Code, "-")
Also, to look at the last element just use:
If secondSplit(Ubound(SecondSplit)) = "456" Then
Subtracting 1 from the ubound would get you the second to last element.
You don't need to split it twice - what you're looking for is Right():
FirstSplit = split("A-456-BC-123;DEF-456;GHI-789",";")
For each code in FirstSplit
If Right(code, 3) = "456" Then
' do something
End If
Next
Though this would also match an entry like ABC-1456. If the - symbol is a required delimiter, you'd have to say If Right(code, 4) = "-456".

Resources