Javascript Split method - javascript

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

Related

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.

How to strip non integers in array elements in JavaScript

I'm quite new to programming, and I feel that similar questions have been asked before. But I've tried to apply them and know I am missing something fundamental.
Given an array:
var myArray = [24.203, 12*45, 000-1, 4567+00];
I'd like to strip all non integers, so that I have something like this:
var myArray = [24203, 1245, 0001, 456700];
I know of the .replace method, but I can't seem to get it work. Here are four things I've tried:
function stripNonIntegers(arr) {
var x;
this.myArray = myArray;
for(x = 0; x < 10; x++) {
myArray[x] = myArray[x].replace(/\D/g, '');
} }
stripNonIntegers(myArray);
This returns an error saying myArray is undefined.
var x;(myArray); { //I don't like the semicolons but I get an error if I omit them
for(x = 0; x < 10; x++)
{myArray[x] = myArray[x].replace(/\D/g, '');
} }
this returns an error saying x is undefined.
stripNonIntegers= function(arr) {
for (x =0; x<this.length; x++)
myArray.replace(/\D/g,'');};
stripNonIntegers(myArray);
This output is undefined.
var stripNonIntegers= myArray[x]; {
for (x=0; x<myArray.length; x++) {
stripNonIntegers = myArray.replace(/[^\d]/g, '');
} }
And this one also says x is undefined. This post explains how to use the .replace method with a regex of /D to strip non-numerics from a string, but I can't seem to get it to work with an array (not a function). Thus I try to stick a 'for' loop in there so it treats each element as its own string. I know I'm making a stupid mistake, but for all my trying, I can't identify it. I'm shooting in the dark.
Any tips? Thanks in advance.
var myArray = ['24.203', '12*45', '000-1', '4567+00'];
var myNewArray = myArray.map(function(value) {
return parseInt(value.replace(/\D/g, ''), 10);
});
\D is a shorthand character class that matches all non-digits.
The above code works when your array elements are strings.
You have the regular expression right, and you're using replace correctly. Your problem may be that the items in your array are not strings in the code you gave. Just wrap each one in quotes to make them strings:
var myArray = ['24.203', '12*45', '000-1', '4567+00'];
Then, you can map over the array and use your replace call:
var newArray = myArray.map(function (item) {
return item.replace(/\D/g, '');
});
That results in this:
["24203", "1245", "0001", "456700"]
These are still strings, though. To convert them to numbers, you can use parseInt:
var intArray = newArray.map(function (item) {
return parseInt(item, 10);
});
You could do all this in one step, if you prefer:
var newIntArray = myArray.map(function (item) {
return parseInt(x.replace(/\D/g, ''), 10);
});
Of course, if you prefer regular for loops, you could do all this with those. However, I think using map looks a bit cleaner. If you're not familiar with map, check out the MDN docs for the array map function

Sizzle push apply

Why would the Sizzle selector engine use push.apply( results.... ) over results.push(...) it seems unnecessary to me. Can someone explain the motivation?
To elaborate, I've become interested in writing/borrowing bits from sizzle for a lighter weight selector engine. I figure I don't need some things like :contains(text) which would reduce the weight even further. So reading through the source I see
var arr = [],
push = arr.push
results = results || [];
....
push.apply( results, context.getElementsByTagName( selector ) );
The code makes sense, except wouldn't it be simpler to use
results.push( context.getElementsByTagName( selector ) );
I don't intend to be naggy about such a minor convention, I just want to know if I'm missing something like a context issue.
It is instead of:
results.concat(array)
Because concat creates an extra array, but push.apply won't:
push.apply(results, array)
The results array is cached and no extra arrays are created.
But you could also do:
results.push.apply(results, array)
I'm not sure why the need for arr.
Edit:
I'm thinking the need for the extra arr might be to convert the pseudo-array that getElementsByTagName returns into a real array.
Looking over the code again (after taking a break). Around line 205, Sizzle checks if the selector pattern is an ID and uses results.push
elem = context.getElementById( m );
results.push( elem );
return results;
Line 237 onwards is for Elements or Classes and uses getElementsByTagName or getElementsByClassName along with push.apply( results, ... ).
I assume its a short hand version of
for( elem in context.getElementsByClassName( m ) ) {
results.push( elem );
}
As is the case in the Mozzila docs example https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
// short hand
var max = Math.max.apply(null, numbers);
var min = Math.min.apply(null, numbers);
/* vs. simple loop based algorithm */
max = -Infinity, min = +Infinity;
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
if (numbers[i] < min)
min = numbers[i];
}
EDIT:
From my original question results.push( context.getElementsByTagName( selector ) ); would result in an unwanted Object. This pushes the one argument of type NodeList into results.
Example:
var a = [1, 2, 3], b = [], c =[];
b.push( a ); // b.length = 1, now we have a multidimensional array
[].push.apply( c, a ); // c.length = 3, we now have a clean array, not a NodeList

How to remove duplicate objects from java script array?

I have two arrays as shown below. I want to remove Array2 elements from Array1. How do I do that?(either in plain java script or using ExtJS)
var Array1 = [];
var Array2 = [];
Array1.push(['eth0'], ['eth1']);
Array2.push(['eth1']);
If you have the array filter function available to you, you can do something like the following:
var filteredArr = Array1.filter(function(val){
return Array2.indexOf(val) != -1;
})
I think this will only be supported in newer browsers, though. It's an elegant way to handle the situation, so you may want to take a look at a library like UnderscoreJS which will include filtering, defaulting to the native implementation if available.
If using UnderscoreJS, the code would look very similar:
var filterdArr = _.filter(Array1, function(val) {return Array2.indexOf(val) != -1});
function removeDupes(a1, a2) {
var index = {}, result = [], i, l;
for (i=0, l=a2.length; i<l; i++) {
index['-' + a2[i]] = "";
}
for (i=0, l=a1.length; i<l; i++) {
if (index['-' + a1[i]] !== "") result.push(a1[i]);
}
return result;
}
The index object is for speedy look-up of values so we can test their existence quickly.
The '-' + is to migrate the fact that values could be things like toString that also exist as object properties. When prefixed with a letter that regular JavaScript identifiers cannot start with, every value will be safe for use as an object key.
Example:
removeDupes([1,2,3,4], [2,4,5]);
// -> [1,3]
removeDupes([2,4,5], [1,2,3,4]);
// -> [5]
Check this link: http://www.developersnippets.com/2008/10/30/remove-duplicates-from-array-using-javascript/. Concat your arrays with concat() and call uniqueArr().

Elegant way to convert string of values into a Javascript array?

I have an ajax request that returns a list of values like this:
"1,2,3,4,5,6"
I need it to be a javascript array with numbers:
[1,2,3,4,5,6]
I tried:
var array = new Array("1,2,3,4,5,6".split(","))
But the numbers are still strings in the output:
["1","2","3","4","5","6"]
Is there a clean way to have it as a numbered array? Preferably without writing a function to iterate through it?
You need to loop through and convert them to numbers, like this:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = +array[i];
Or, the more traditional example:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = parseInt(array[i], 10);
A more jQuery-centric approach using jQuery.map():
var str = "1,2,3,4,5,6";
var arr = $.map(str.split(","), function(el) { return parseInt(el, 10); });
Not sure if this counts as writing a function but you can use the map function in jquery. I saw you listed as a tag so I assume you are using:
var stringArray = "1,2,3,4,5,6".split(",");
var numberArray = $.map(stringArray,
function(item, i)
{
return parseInt(item, 10);
});
// jquery must have a way to do what any modern browser can do:
var str= "1,2,3,4,5,6";
var arr= str.split(',').map(Number);
// returns an array of numbers
If you trust the ajax response, and if (for whatever reason) you're committed to not using a loop, you can always go with eval:
var str = "1,2,3,4,5,6";
var array = eval("[" + str + "]");
If you don't wish to expliclty iterate you can use array.map, javascripts map function.
array.map(callbackFunc, array);
var arr = array.map(function(x) {return parseInt(x);}, "1,2,3,4,5,6".split(","));
http://www.tutorialspoint.com/javascript/array_map.htm
Theres probably a better reference somewhere but I don't us javascript enough to have a good favorite reference site.
EDIT - i see jQuery has its own map, thats probably worth looking into.

Categories

Resources