a code which reverses null terminated string - javascript

I am new to js.
I am trying to write a code which reverses null terminated string.
I tried writing using push and pop.
but i am not getting output, can you tell me what is the problem.
providing code below
var word = "Cell0";
//var char = word.stringCharAT();
for (i=0; i< word.length; i++) {
var pushWord = [];
pushWord.push(word[i]);
for (j=0; j< pushWord.length; j++) {
var reverseWord= [];
reverseWord = pushWord[j].pop;
console.log("reverseWord" + reverseWord);
}
}

Here's a solution.
var word = "Cell0";
var reversed = '';
for (var i = word.length-1; i >= 0; i--) {
reversed += word[i];
}
console.log(reversed);
This loops through the characters of the string in reverse and adds the characters to a new string.

pushWord[j] is not an array, .pop is not called.
Define pushWord and reverseWord arrays outside of for loop, within loop, after word[i] is pushed to pushWord, call .unshift() on reverseWord with pushWord[pushWord.length -1] as parameter.
var word = "Cell0";
var pushWord = [];
var reverseWord = [];
for (let i = 0; i < word.length; i++) {
pushWord.push(word[i]);
reverseWord.unshift(pushWord[pushWord.length - 1]);
}
console.log("reverseWord" + reverseWord);

var originalWord = "Cell0";
var reverseWord = [];
for (let i = 0; i < originalWord.length; i++) {
reverseWord.unshift(originalWord [i]);
}
console.log(reverseWord.join(''));
You don't even need to push.
Another way to achieve the result!

Related

Ho to reverse split string into a JavaScript array?

I want to use one loop to split or explode a string into an array like
"Work" // -> var strArray = [k, rk, ork, work]
I tried for loop, but I know this is not an efficient.
for (let index = 0; index < word.length; index++)
{
strArray.push(word[word.length - 1]);
}
Any idea?
It looks like you may want to be sliceing your string. Here's something that'll do that:
function wordSplit(word) {
let strArray = [];
for (let i = 0; i < word.length; i++) {
strArray.push(word.slice(i));
}
return strArray;
}
And a fiddle: https://jsfiddle.net/13kephm9/7/
You can split the string, and iterate the array with Array#map, and generate the string using slice:
var word = 'work';
var result = word.split('').map(function(l, i) {
return word.slice(-i - 1);
});
console.log(result);
for (let index = 0; index < word.length; index++)
{
strArray.push(word.slice(index));
}
array string elements reversing
function rev(arr){
var text = new Array;
for(var i= arr.length-1;i>= 0;i--){
text.push(arr[i]);
}
return text.join();
}
console.log(rev(["a","b","c"]));
`print`

Creating an array without hard-coding

I'm trying to create an array of strings and produce the possibilities by the length of array string. For example:
var someStr = ["a","b","c","d"];
//I want to produce this outcome
a
ab
abc
abcd
b
bc
bcd
c
cd
d
I know I can get the # of possibilities for "a" only by this way:
var numCombinations = 0;
var comboString = '';
var outcome = [];
for(var i = 0; i < someStr.length; i++){
comboString += someStr[i];
outcome[i] = comboString;
numCombinations += i; //# of combinations from above
}
But how would I continue with these variables for the left over possibilities? I've thought of creating nested for-loops again and again but that would eventually lead to the (n)th length with hard-coding. Would there be any method(s) to create this and store all the possibilities to the (n)th length?
Hope this help.
function getComboStringListFromIdx(arr, idx){
var result = [];
var comboString = '';
for(var i=idx; i<arr.length; i++){
comboString += arr[i];
result.push(comboString);
}
return result;
}
var someStr = ['a','b','c','d'];
var outCome = [];
for(var i = 0; i<someStr.length; i++){
outCome = outCome.concat(getComboStringListFromIdx(someStr, i));
}
I will also use nested for-loop ! One is normal looping and other is to skip less than current index from first loop !!
var someStr = ["a","b","c","d"];
for(var i = 0;i < someStr.length;i++) {
output(i);
}
function output(index) {
var str = "";
for(var j in someStr) {
if(j < index) {
continue;
}
str += someStr[j];
console.log(str);
}
}
This solution uses a nested for loop and skips concatenation on the first element of the nested for loop.
var arr = ["a","b","c","d"];
for(var i=0;i<arr.length;i++){
var str = arr[i];
for(var j=i;j<arr.length;j++){
if(i!==j)
str+=arr[j];
console.log(str);
}
}
https://jsfiddle.net/fmy539tj/

Alternately Join 2 strings - Javascript

I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source

Efficient way to turn a string to a 2d array in Javascript

I need to check from a string, if a given fruit has the correct amount at a given date. I am turning the string into a 2d array and iterating over the columns.This code works, but I want to know : is there a better way to do it? I feel like this could be done avoiding 4 for loops.
function verifyFruit(name, date, currentValue) {...}
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var rows = data.split('\n');
var colCount = rows[0].split(',').length;
var arr = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < colCount; j++) {
var temp = rows[i].split(',');
if (!arr[i]) arr[i] = []
arr[i][j] = temp[j];
}
}
for (var i = 1; i < colCount; i++) {
for (var j = 1; j < rows.length; j++) {
verifyFruit(arr[0][i], arr[j][0], arr[j][i]);
}
}
This would be a good candidate for Array.prototype.map
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var parsedData = data.split("\n").map(function(row){return row.split(",");})
What map does is iterate over an array and applies a projection function on each element returning a new array as the result.
You can visualize what is happening like this:
function projection(csv){ return csv.split(",");}
var mappedArray = [projection("Date,Apple,Pear"),projection("2015/04/05,2,3"),projection("2015/04/06,8,6")];

Splitting to 2D array

How I can split a string into 2D array. String is like
1c2c3r4c5c6r6c8c9
array should be like
[[1,2,3],
[4,5,6],
[7,8,9]]
var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/);
for (var i = 0; i < rows.length; i++)
rows[i] = rows[i].split(/c/);
Please note that I didn't test this so it might contain a syntax error or something...
You can use the map method on Array
var s = "1c2c3r4c5c6r6c8c9";
var rows = s.split("r");
result = rows.map(function (x) {
return x.split('c');
}));
map is introduced in ECMAScript5 and is not supported in older browsers. But, there is a decent work-around here
var str = "1c2c3r4c5c6r6c8c9";
var result = [];
var group = str.split("r");
for(i in group) {result.push(group[i].split("c"))};
result should be what you want.
This should work:
var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/g);
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(/c/g);
for (var j = 0; j < cells.length; j++) {
cells[j] = parseInt(cells[j]);
}
rows[i] = cells;
}

Categories