Spaces in a joined array [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have been working on a ceaser cipher algorithm but I haven't been able to grasp the reason why the joined array returns spaces in a peculiar state.
function rot13(str) { // LBH QVQ VG!
var string = str.split('');
var codedStr = [];
var encoded = [];
for (var k=0; k < string.length; k++){
codedStr.push(string[k].charCodeAt());
}
for(var i = 0; i < codedStr.length; i++){
if(codedStr[i] > 77 ){
codedStr[i] -= 13;
}
else if( codedStr[i] == 32 || codedStr[i] == 63){
codedStr[i] = codedStr[i];
}
else{
codedStr[i] += 13;
}
encoded.push(codedStr[i]);
}
var decode = codedStr.map(String.fromCharCode);
var result = decode.join('');
return result;
}
// Change the inputs below to test
console.log(rot13("SERR PBQR PNZC"));

String.fromCharCode accepts multiple arguments, and map provides 3. You should use
codedStr.map(code => String.fromCharCode(code));

Related

JavaScript: How to create a function that receives an array of numbers and returns an array containing only the positive numbers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
What is Wrong with this Code? I should create a function that receives an array of numbers and returns an array containing only the positive numbers. How can it be modified? Especially Modified. Not another code!
all = prompt("Give me an array of numbers seperated by ','");
var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
var positive = [];
for(var i = 0; i < splitted.length; i++);{
var el = splitted[i];
if (el >= 0){
positive.push(el);
}
}
return positive;
}
var positive = returner(splitted);
print(positive);
First I noticed that you are using print to check your output - that should be console.log().
But your real mistake is the semicolon after the for bracket in line 7.
Here is a working code-snippet:
let all = prompt("Give me an array of numbers seperated by ','");
let splitted = all.split`,`.map(x => +x);
function returner(splitted) {
let positive = [];
for (let i = 0; i < splitted.length; i++) {
const el = splitted[i];
if (el >= 0) {
positive.push(el);
}
}
return positive;
}
var positive = returner(splitted);
console.log(positive);
Just remove the semicolon after the for statement as:
all = prompt("Give me an array of numbers seperated by ','");
var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
var positive = [];
for(var i = 0; i < splitted.length; i++){
var el = splitted[i];
if (el >= 0){
positive.push(el);
}
}
return positive;
}
var positive = returner(splitted);
console.log(positive);
practically with that semicolon you were doing "nothing" n times and then executing the block on it's own which didn't help filling your array since the i variable is already passed the last index of the array and so splitted[i] results to undefined which is not >=0 thus nothing gets pushed to the positive array.
(also I'd imagine you want a console.log at the end instead of print? )
Why don't you use filter?
var array = [3, -1, 0, 7, -71, 9, 10, -19];
const getpositiveNumbers = (array) => array.filter(value => value > 0);
var positives = getpositiveNumbers(array);
console.log(positives);
Anyway, as #trincot noticed, your code is wrong.

Get palindrome length from string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have one string as "testaabbaccc" in this string we contain palindrome as "abba" and it's length is 4 but how can we identify this with a JavaScript code.
var string ="testaabbaccc"
Need Output as abba is palindrome and length is 4
You can use this article and modify it to your needs.
Working demo
function isPalindrome(s) {
var rev = s.split("").reverse().join("");
return s == rev;
}
function longestPalind(s) {
var maxp_length = 0,
maxp = '';
for (var i = 0; i < s.length; i++) {
var subs = s.substr(i, s.length);
for (var j = subs.length; j >= 0; j--) {
var sub_subs = subs.substr(0, j);
if (sub_subs.length <= 1)
continue;
if (isPalindrome(sub_subs)) {
if (sub_subs.length > maxp_length) {
maxp_length = sub_subs.length;
maxp = sub_subs;
}
}
}
}
return maxp;
}
console.log(longestPalind("testaabbaccc"));
console.log(longestPalind("testaabbaccc").length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Javascript: Find the second longest substring from the given string Ex: I/p: Aabbbccgggg o/p: bbb [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Javascript:Find the second longest substring from given string(input and output example added in heading)
Try this
Get sequences using RegExp
Sort them based on string length
Select second Item
function getSecondSubstring(str){
let regex = new RegExp(str.toLowerCase().split("").filter((x,i,a)=>a.indexOf(x)===i).join("+|")+"+", "ig")
let substrgroups = str.match(regex);
substrgroups.sort((a,b)=> b.length-a.length);
return substrgroups[1]
}
console.log(getSecondSubstring("ööööööðððób"));
console.log(getSecondSubstring("Aabbbccgggg"));
If you don't mind using regular expressions:
function yourFunctionName(input){
let grp = input.split(/(?<=(.))(?!\1|$)/ig);
grp.sort((a,b)=> b.length-a.length);
if(grp.length <= 0){
return null;
}
else if (grp.length == 1){
return grp[0];
}
else{
grp.sort(function(a, b){
return b.length - a.length;
});
return grp[1];
}
}
console.log(yourFunctionName("ööööööðððób"));
Or another way which does not use regular expressions...
function yourFunctionName(input){
input = input.toLowerCase();
let counter = [];
let prevChar;
let countIndex = 0;
for (let index = 0, length = input.length; index < length; index++) {
const element = input[index];
if(prevChar){
if(prevChar != element){
countIndex++;
counter[countIndex] = "";
}
}
else{
counter[countIndex] = "";
}
counter[countIndex] += element;
prevChar = element;
}
if(counter.length <= 0){
return null;
}
else if (counter.length == 1){
return counter[0];
}
else{
counter.sort(function(a, b){
return b.length - a.length;
});
return counter[1];
}
}
console.log(yourFunctionName("aaaaabbbbccdd"));

Need to add one by one value to comma separated List from array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need to add one bye one value to comma separated list
my code
var Plist, Llist;
for (var i = 0; i < results.length; i++) {
var id = results[i].id;
if (id.startsWith("P")) {
Plist = // Add comma separated value
} else if (id.startsWith("L")) {
Llist = // add comma repeated value
}
}
please suggest better solution...
var Plist = "", Llist = "";
for (var i = 0; i < results.length; i++) {
var id = results[i].id;
if (id.startsWith("P")) {
Plist += id + ",";
} else if (id.startsWith("L")) {
Llist += id + ",";
}
}
if (Plist.indexOf(',') !== -1) {
Plist = Plist.substring(0, Plist.length - 1);
}
if (Llist.indexOf(',') !== -1) {
Llist = Llist.substring(0, Llist.length - 1);
}

convert string to array of numbers in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How to convert below String into arrays in javascript
var data = "[
[[1400586475733,-1],
[1400586535736,-1],
[1400586595739,-1],
[1400586655742,-1],
[1400586715745,-1]],
[[1400586475733,0],
[1400586535736,0],
[1400586595739,0],
[1400586655742,0],
[1400586715745,0]]
]";
expected output is
data[0] = [[1400586475733,-1],[1400586535736,-1],[1400586595739,-1],[1400586655742,-1],[1400586715745,-1]]; ==> of type object Array
data[0][0] = 1400586475733 ==> of type number
data[0][1] = -1 ==> of type number
I haven't tried it out thoroughly, but it should work:
var string = "[[[1400586475733,-1],[1400586535736,-1],[1400586595739,-1],[1400586655742,-1],[1400586715745,-1]],[[1400586475733,0],[1400586535736,0],[1400586595739,0],[1400586655742,0],[1400586715745,0]]]";
var dataFromString = string.split(",");
var finalArray = [];
var arrayStartRegEx = new RegExp(/^\[/);
var arrayEndRegEx = new RegExp(/\]$/);
var currentArray = finalArray;
var arrayHistory = [];
for(var i = 0; i < dataFromString.length; i++) {
var currentString = dataFromString[i];
var closingArray = false;
while(arrayStartRegEx.test(currentString) === true) {
// Save previous array
// createArray
// add to big array
// currentArray = createdArray
// remove bracket
var arr = []
arrayHistory.push(currentArray);
currentArray.push(arr);
currentArray = arr;
currentString = currentString.slice(1,currentString.length - 1);
}
while(arrayEndRegEx.test(currentString) === true){
// remove bracket
// add element to array
// close currentArray
// currentArray = big array
currentString = currentString.slice(0,-1);
if(!closingArray) {
var string = currentString.replace(/\]/g, '');
// Use parseFloat if you know it's going to be a float
currentArray.push(parseInt(string));
closingArray = true;
}
currentArray = arrayHistory.pop();
}
if(arrayStartRegEx.test(currentString) === false && arrayEndRegEx.test(currentString) === false) {
// add element to array
currentArray.push(parseInt(currentString))
}
}
console.log(finalArray);

Categories

Resources