Removing return carriage from an array - Javascript - javascript

I have array as shown below:
["↵", "Oh", "yeah,", "did", "we", "mention", "it’s", "free?↵"]
Is there a way I can remove that ↵ from the string and from the array?
I tried
str.replace(/(\r\n|\n|\r)/gm,"");
This didn't help.

Simply split your string on /\s+/, then you don't need to perform this action anymore.
var str='\nOh yeah, did we mention it’s free?\n';
var arr=str.split(/\s+/);
Note: you might want to trim \s+ from the beginning and end of the string fist. (Older) Browsers that do not support trim() can use:
arr=str.replace(/^\s+|\s+$/g, '').split(/\s+/);
Strictly answering your question how to remove 'carriage returns' from strings in an array:
// you have:
var str= '\nOh yeah, did we mention it’s free?\n';
var arr= str.split(' ');
// no function needed, a simple loop will suffice:
for(var L=arr.length; L--; arr[L]=arr[L].replace(/[\n\r]/g, ''));
Note that (as can already be seen in your example as array-item 0) you might end up with some empty strings (not undefined) in your array.

You can clean up your array from empty strings using String.prototype.trim combined with Array.prototype.filter to remove falsy values. For example:
var arr = ["\n", "", "Oh", "yeah,", "did", "we", "mention", "it’s", "free?\n"]
// check array before
alert(JSON.stringify(arr));
arr = arr.map(function(el) {
return el.trim();
}).filter(Boolean);
// after cleaning up
alert(JSON.stringify(arr));

Try this:
function removeReturn(ary){
var b = [], a = [];
for(var i=0,l=ary.length; i<l; i++){
var s = ary[i].split('');
for(var n=0,c=s.length; n<c; n++){
if(s[n] === '\u021B5')s[n] = '';
}
b.push(s.join(''));
}
for(var i=0,l=b.length; i<l; i++){
var x = b[i];
if(x !== '')a.push(x);
}
return a;
}

Related

How to remove substring and comma if exist on left or right side

I have the following string:
"house,car,table"
I need to properly handle the comma removal, so much so that If I remove "car" the output should be:
"house,table"
If I remove "table" the output should be:
"house,car"
You can use the .split() in an array then .filter() out the target text after words .join() to create a string.
var str = "house,car,table";
str = str.split(',').filter(x => x !== 'car').join(',');
console.log(str)
You can use string#split, string#indexOf array#splice and arr#join
var str = "house,car,table";
var arr = str.split(',');
var index = arr.indexOf('car');
arr.splice(index, 1);
console.log(arr.join(','));
There are several ways. #Satpal has offered a way that is optimized. but another way:
var array ="house,car,table";
var arraySplit = array.split(",");
var newArray = [];
for (i=0; i<arraySplit.length; i++)
{
if (arraySplit[i] != "car")
{
newArray.push(arraySplit[i]);
}
}
var joinedArray = newArray.join(",");
console.log(joinedArray);
function format(name){
var nameStr="house,car,table";
if(nameStr.indexOf(name)==-1)return -1;
nameStr+=",";
nameStr=nameStr.replace(name+",","");
return nameStr.substring(0,nameStr.length-1);
}
console.log(format("house"));
console.log(format("table"));

Why is my code pushing every permutation twice?

I'm confused as to why my code is pushing every permutation twice. Please someone help. I'm using heap's algorithm:
var regex = /(.)\1+/g;
function permAlone(str) {
var newArray = str.split('');
var n = newArray.length;
var permutations = [];
var tmp;
function swap(index1, index2) {
tmp = newArray[index1];
newArray[index1] = newArray[index2];
newArray[index2] = tmp;
}
function generate(n, newArray) {
if (n === 1) {
permutations.push(newArray.join(''));
} else {
for(var i = 0; i<n-1; i++) {
generate(n-1, newArray);
swap(n % 2 ? 0 : i, n-1);
permutations.push(newArray.join(''));
}
generate(n-1, newArray);
}
}
generate(n, newArray);
return permutations;
}
permAlone('aab');
The array that is returned is:
["aab", "aab", "aab", "baa", "baa", "aba", "aba", "aba", "baa", "baa"]
So as you can see, the permutations are appearing many more times than intended for each thing. Any help would be great
The code's a little complex and it's difficult to track given the recursion, but if all you want is an array with only unique values, you can simply apply the following code to the result array:
function stripDuplicates(input) {
if (!input || typeof(input) !== 'object' || !('length' in input)) {
throw new Error('input argument is not array.');
}
var newArray = [];
for (var i = 0; i < input.length; i++) {
if (newArray.indexOf(input[i]) === -1) {
newArray.push(input[i]);
}
}
return newArray;
}
This could also be done functionally rather than imperatively, but that's really more of a preference than an optimization issue.
Bálint also points out that you could merely convert the result to a Set, then convert the Set back to an Array, which would automatically strip out any duplicates. Beware, though, that Set is a comparatively new affordance in Javascript and will not function in pre-ES6 environments.
You have a call to:
permutations.push(newArray.join(''));
inside of your for loop. That shouldn't be there. And then, of course if you are permuting strings that have duplicate characters, well, expect to see dupes. e.g., if you permute the string "aa" you'll get two entries from this algorithm "aa" and "aa". Heap's algorithm doesn't try to remove dupes, it treats each element as unique within the string. Obviously, it's trivial to use remove dupes if that's something you care about doing.

concat empty / single item array

Ok, so I have this simple code :
for(var i=0; i<lines.length; i++) {
elements += myFunction(lines[i]);
}
Where elements is an empty array at the start and myFunction() is just a function that returns an array of strings.
The problem is that if myFunction() returns an array with a single string, the += is interpreted as a string concat in place of an array concat.
At the end of the loop the result is just a long string and not an array.
I tried push()ing the values in place of concatenation, but this just gives me a two dimensional matrix with single item arrays.
How can I solve this typecasting problem ? Thank you in advance !
Try :
for(var i=0; i<lines.length; i++) {
elements [i] = myFunction(lines[i]);
}
I suppose it solves the problem.
You can use the Array concat function:
elements = elements.concat(myFunction(lines[i]));
Presumably you want something like:
var arrs = [[0],[1,2],[3,4,5],[6]];
var result = [];
for (var i=0, iLen=arrs.length; i<iLen; i++) {
result = result.concat(arrs[i]);
}
alert(result); // 0,1,2,3,4,5,6
Ah, you want to concatenate the results of a function. Same concept, see other answers.
You can also use myArray[myArray.length] = someValue;
let newArray = [].concat(singleElementOrArray)

Simple way to import and export and store Arrays

For example I have something like this.
var Ar : Array;
Ar[0] = 'apple';
Ar[3] = 'pineapple';
Ar[12] = 'car';
Ar[33] = 'dog';
Ar[41] = 'cat';
Ar[21] = 'apple';
And I need to store it in simple text file. Like this
ArText : String ;
ArtText = "0-Apple,3-pineapple,12-car,33-dog,41-cat,21-apple"
You got the point.
What is best way to convert Array in to a readable string, and then back? Javascript code will be best, but you can use almost any similiar.
My initial impulse was to convert it directly to JSON, but then I realised that JSON.stringify() would return something like this:
["apple",null,null,"pineapple",null,null,null,null,null,null,null,null,"car",null,null,null,null,null,null,null,null,"apple",null,null,null,null,null,null,null,null,null,null,null,"dog",null,null,null,null,null,null,null,"cat"]
Because your array has a bunch of undefined slots that all become null because JSON doesn't support undefined values. Which would be OK if you just need to store it except then when you convert it back to an array you'd end up with nulls everywhere instead of undefined so you'd have to allow for that (not a big deal) but in any case it sounds like you want it to be human-readable too.
So instead I suggest you convert it to an object and then convert the object to JSON using JSON.stringify(). To convert it back you use JSON.parse() to turn your string into an object, then loop through the object properties to create a sparse array.
What I'm proposing would result in a JSON string like this:
{"0":"apple","3":"pineapple","12":"car","21":"apple","33":"dog","41":"cat"}
The code:
function sparseArrayStringify(arr) {
var obj = {},
i;
for (i=0; i < arr.length; i++)
if (typeof arr[i] != "undefined")
obj[i] = arr[i];
return JSON.stringify(obj);
}
function parseToSparseArray(str) {
var arr = [],
obj = JSON.parse(str),
k;
for (k in obj)
arr[k] = obj[k];
return arr;
}
var stringifiedArray = sparseArrayStringify(Ar); // where Ar is your array
// and change it back
var anArray = parseToSparseArray(stringifiedArray);
Working demo: http://jsfiddle.net/XXqVD/
Note: in my parseToSparseArray() function I didn't bother testing that the properties of the object in the string being parsed actually are non-negative integers, but you can add that if desired.
Newer browsers support the JSON object with associated methods, or for older browsers you can include the json2.js library.
By the way, the code in your question is invalid JavaScript: you can't declare variables with a type in JS. See the examples in my code for how to declare arrays, objects, etc.
EDIT: OK, I don't know why on earth you'd want the non-JSON version when JSON is a well known standard format, but here are some untested functions that read and write exactly the format from the question:
"0-Apple,3-pineapple,12-car,33-dog,41-cat,21-apple"
Note that your proposed format won't work if any of the array elements contain commas or hyphens. Which is why JSON is the way you should go. Anyway:
function serialiseArray(arr) {
var workingArray = [],
i;
for (i=0; i < arr.length; i++)
if (typeof arr[i] != "undefined")
workingArray.push(i + "-" + arr[i]);
return workingArray.join(",");
}
function deserialiseArray(str) {
var arr = [],
items = str.split(","),
item,
i;
for (i=0; i < items.length; i++) {
item = items[i].split("-");
arr[item[0]] = item[1];
}
return arr;
}
If it's just strings in the array, you could use the join() method on the Array object to create a comma separated string, and then use the split() method on the String object to convert the string back to an array.
var Ar = new Array;
Ar[0] = 'apple';
Ar[3] = 'pineapple';
Ar[12] = 'car';
Ar[33] = 'dog';
Ar[41] = 'cat';
Ar[21] = 'apple';
var stringRepresentation = Ar.join(",");
var backToArray = stringRepresentation.split(";");
You can see this working here; http://jsfiddle.net/ykQRX/. Note I've also fixed your invalid JavaScript (var Ar = new Array;).

Javascript Split method

var string = abc123;
string.split(*POSITION=3)???
Is there a way to split this string into an array of strings that is [abc,123]?
Is the split method the right thing to use?
I would say the split method is not the right thing to use here, as its purpose is to segment a string based on a certain character.
You could certainly write your own function, of course:
function partition(str, index) {
return [str.substring(0, index), str.substring(index)];
}
// results in ["123", "abc"]
var parts = partition("123abc", 3);
If you wanted to write "123abc".partition(3) instead, you could make that possible by extending String.prototype:
String.prototype.partition = function(index) {
return [this.substring(0, index), this.substring(index)];
};
Personally, though, I'd recommend avoiding that sort of tomfoolery (search the web for "extending built-in objects in JavaScript" if you want to read what others have to say on the topic).
Maybe use a simple RegExp match?
var arr = "abc123".match(/^([a-z]+)(\d+)$/i);
arr.shift();
console.log(arr);
var arr = "this is a test".match(/.{1,3}/g);
No but it is trivial to implement that:
function splitn( str, n ){
var r = [], offset = 0, l = str.length;
while( offset < l ) {
r.push( str.substr( offset, n ) );
offset += n;
}
return r;
}
Then:
var string = "abc123";
console.log( splitn( string, 3 ) );
//["abc", "123"]
Assuming you want similar functionality to str_split

Categories

Resources