String manipulation - removing an element from a list - javascript

I have a comma separated list of values, and I need to remove the one that is equal to a certain value.
myList = '10,20,30';
myList.remove(20); // === '10,30'

I'm dashing off, but the component parts of the solution will probably be:
String#split, which splits a string into an array based on a delimiter.
Array#indexOf, which finds an entry in an array (some older browsers may not have it; on those, you'll have to do a loop).
Array#splice, which (amongst other things) removes entries from an array.
Array#join, which joins an array into a string using a given delimiter.
...possibly with something mixed in there to deal with stray spaces, if they're a possibility.
Or of course, you could just put commas at either end and then search for ",20," with String#indexOf and use String#substring to grab the bits in front of and behind it. But what fun is that. ;-) (And it seems a bit fragile.)

Here is some tested and jslinted code that does what you're asking for.
if (!String.prototype.removeListItem) {
String.prototype.removeListItem = function(value, delimiter) {
delimiter = delimiter || ',';
value = value.toString();
var arr = this.split(delimiter),
index = arr.indexOf(value);
while (index >= 0) {
arr.splice(index, 1);
index = arr.indexOf(value);
}
return arr.join(delimiter);
};
}
alert('10,20,30,120,200'.removeListItem(20));
// yields '10,30,120,200'
However, I question why you would do this. Arrays should be stored in array objects, not in string literals. If you need to display the list, then convert to a delimited list at display time. If your input is a string, then split it at input time and keep it internally as an array. I really strongly believe this is the best practice for you and in the long run you will have much easier to maintain code that is much easier to understand.

var myArray = myList.split(',');
myArray.splice(1,1); // Remove one element at index 1, which is 20 in your example
myList = myArray.toString();

A few people almost had replace working.
var lists = ['20', '10,20', '20,30', '10,20,30', '120,200,2020'];
for (var i=0; i<lists.length; ++i) {
lists[i] = lists[i].replace(/(^|,)20,|(^|,)20$/,'$1');
}
Result:
["", "10", "30", "10,30", "120,200,2020"]

Split the string to give you an array. Once you have it in an array, remove the element you need removed. Then output the string again.
Or you could find and replace '20', with ''.

Related

Using method sort() for sorting symbols in element of array

I need to sort an element cinema of array arr by symbols unicode (in the output it must been like "aceinm"). I know that in this case we need to use method sort(). But I do know how inject sort method for array element.
Please, help. Code below are not working.
Error: arr[1].sort is not a function.
var arr = ["cinema"];
arr[1].sort();
console.log(arr[1]);
If you want to sort your string, you can easily do this by splitting and joining the string.
"cinema".split ("").sort ().join ("")
// aceimn
Or, in your case:
arr[0] = arr [0].split ("").sort ().join ("")
// arr: ["aceimn"]
If you need to sort all strings in an array, use map ().
arr = arr.map (itm => itm.split ("").sort ().join (""))
You are referring arr[1] which is not available also you have to split in order to sort the letters.
var arr = ["cinema"];
var sorted = arr[0].split('').sort();
console.log(sorted, sorted.join(''));
This should do what you want:
var arr = ["cinema"];
console.log(arr[0].split("").sort().join(""));
EDIT: I see the same solution has been proposed by several others. I'll expand a bit on it.
Since you want to sort by the letters in the word cinema, and cinema is at index 0, you get the string "cinema" by calling arr[0], and then split the string with the method .split(""). This turns the string into an array that you can .sort() in the way you attempted initially.
The error you got, "Error: arr[1].sort is not a function", tells you that .sort() is not a function of the string element. Once you've turned the string into an array (for example with .split()), the .sort() function becomes available.

producing a word from a string in javascript

I have a string which is name=noazet difficulty=easy and I want to produce the two words noazet and easy. How can I do this in JavaScript?
I tried var s = word.split("=");
but it doesn't give me what I want .
In this case, you can do it with that split:
var s = "name=noazet difficulty=easy";
var arr = s.split('=');
var name = arr[0]; //= "name"
var easy = arr[2]; //= "easy"
here, s.split('=') returns an array:
["name","noazet difficulty","easy"]
you can try following code:
word.split(' ').map(function(part){return part.split('=')[1];});
it will return an array of two elements, first of which is name ("noazet") and second is difficulty ("easy"):
["noazet", "easy"]
word.split("=") will give you an array of strings which are created by cutting the input along the "=" character, in your case:
results = [name,noazet,difficulty,easy]
if you want to access noazet and easy, these are indices 1 and 3, ie.
results[1] //which is "noazet"
(EDIT: if you have a space in your input, as it just appeared in your edit, then you need to split by an empty string first - " ")
Based on your data structure, I'd expect the desired data to be always available in the odd numbered indices - but first of all I'd advise using a different data representation. Where is this string word coming from, user input?
Just as an aside, a better idea than making an array out of your input might be to map it into an object. For example:
var s = "name=noazet difficulty=easy";
var obj = s.split(" ").reduce(function(c,n) {
var a = n.split("=");
c[a[0]] = a[1];
return c;
}, {});
This will give you an object that looks like this:
{
name: "noazert",
difficulty: "easy"
}
Which makes getting the right values really easy:
var difficulty = obj.difficulty; // or obj["difficulty"];
And this is more robust since you don't need to hard code array indexes or worry about what happens if you set an input string where the keys are reversed, for example:
var s = "difficulty=easy name=noazet";
Will produce an equivalent object, but would break your code if you hard coded array indexes.
You may be able to get away with splitting it twice: first on spaces, then on equals signs. This would be one way to do that:
function parsePairs(s) {
return s.split(' ').reduce(
function (dict, pair) {
var parts = pair.split('=');
dict[parts[0]] = parts.slice(1).join('=');
return dict;
},
{}
);
}
This gets you an object with keys equal to the first part of each pair (before the =), and values equal to the second part of each pair (after the =). If a string has multiple equal signs, only the first one is used to obtain the key; the rest become part of the value. For your example, it returns {"name":"noazet", "difficulty":"hard"}. From there, getting the values is easy.
The magic happens in the Array.prototype.reduce callback. We've used String.prototype.split to get each name=value pair already, so we split that on equal signs. The first string from the split becomes the key, and then we join the rest of the parts with an = sign. That way, everything after the first = gets included in the value; if we didn't do that, then an = in the value would get cut off, as would everything after it.
Depending on the browsers you need to support, you may have to polyfill Array.prototype.reduce, but polyfills for that are everywhere.

Sending an array with JavaScript to the next page

The combination of my methods of declaring an array, adding elements to the array and applying the method toString() does not work. Essentially I enter a certain number (between one and five) values to textvariables : fontVorto1, fontVorto2, fontVorto3 ……… in the html-part of the document.
When I decide on leaving the remaining textelements empty, I click on a button, to assign them to an array, by way of the following function:
function difinNombroFv () {
var fontVortoj = new array();
fontVortoj[0] = document.getElementsByName("fontVorto1")[0].value;
fontVortoj[1] = document.getElementsByName("fontVorto2")[0].value;
fontVortoj[2] = document.getElementsByName("fontVorto3")[0].value;
……………….
and put them together in a string:
x = fontVortoj.toString();
document.getElementsByName("fontVorto")[0].value = x;
(the extra variable x is not needed) to enable me sending them to the next document, where I want to unserialize them with
$fontVortoj = unserialize($_POST["fontVorto"]);
I tested the method toString() by insering an alert(x), but the result was that I got for x the value of "fontVorto1" only.
I met solutions with JSON, jQuery etc., but I never used those "languages", only HTML, JavaScript, PHP.
Will my Christmas day be spoiled because of this simple problem ;>)?
couple of things to note:
1. var fontVortoj = new array(); . here new array() is not correct. it should be:
var fontVortoj = new Array();
now if you call fontVortoj.toString(), then it will convert the array and return a string with array elements separated by comma.
you can rebuild the array from the string in php by using "explode" function.
you can rebuild the array from the string in javascript by using "split" function.
Apparently I misunderstood the question to begin with.
To serialize an astray, you can use .join()
By default, it will give you the values, joined by commas.
To deserialize, use .split()
If there's a chance that there might be commas in your values, choose a more elaborate string for joining:
var ar = ["a", "b"];
var serialized = ar.join("|"); // "a|b"
var deserialized = serialized.split("|"); //["a", "b"]
The string that you use for joining and splitting can be as long as you like.
If you want to be completely covered against any values, then you need to look at JSON.stringify() & JSON.parse(). But that had browser compatibility issues.

JavaScript Split, change parts number

I have a dynamically generated large string which I am splitting.
var myString="val1, val, val3, val4..... val400"
I do a simple split on this string,
myString= myString.split(',')
getting the following:
myString[1] // gives val1
myString[2] // gives val2
myString[3] // gives val3
.
.
.
myString[400] // gives val400
Is there a way to make the following?
myString[101] // gives val1
myString[102] // gives val2
myString[103] // gives val3
.
.
.
myString[500] // gives val400
Arrays are zero-based, so in fact in your version you have indices 0 up to 399 rather than 1 to 400.
I'm not quite sure why you'd want 100 items padding out the start of the array, but for what it's worth, here's a short way of doing what you want. It's also one of the few times the Array constructor is actually useful:
var parts = new Array(100).concat(myString.split(','));
We can add elements at the beginning of an array by using the unshift() method. Here is the general syntax for using it.
scripts.unshift("VAL01","VAL02");
Here scripts is our array object, and we are adding two new elements, VAL01 and VAL02, at the beginning of this array by using the unshift() method.
So you can use unshift to add 100 array elements before your split string.
If you don't want 100 padding elements at the beginning (index 0 to 99), you don't want to use an array. Arrays are always continious with the indexes. So you are probably looking for an object.
var obj = {}
for ( var i = 0; i < arr.length; i++ )
{
obj[ i + 100 ] = arr[i];
}
However you shouldn't do it like that, because using an object reduces your possibilities to work with. If you don't want to add another 100 elements at the beginning (in which case you can just add those to the beginning of the existing array), then you should rather work with the original array and simply shift the index manually when you access it.
Are you sure that you need this? You could simply substract 100 from your offset to get to that value. To this, arrays in JavaScript are zero-indexed. Which means that the first item can be accessed using myString[0] rather than myString[1].
Use a function to read the offset value
function getOffSetValue(arr, index, offset)
{
if(offset == undefined)
offset = 100;
return arr[index - offset];
}
var st = "val1,val2,val3,val4,val5";
var a = st.split(',');
console.log(getOffSetValue(a, 102));

How to manipulate string in an array

I have an array that contain some fields
like this
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_18
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_19
I want to create a new array or manipulate this array to contain only
sid = {25,26,27}
from
_SID_25
_SID_26
_SID_27
where sid will be my array containing sid's extracted from above array
with pattern _SID_
I have to do this in jquery or javascript
use jquery map + regexp
var arr= ['tl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_26_SortOrder_18',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_27_SortOrder_19']
var out = $(arr).map(function(){
return this.match(/SID_(.*?)_/)[1];
});
out should be an array of the values..
(assuming all the values in the array do match the pattern)
I would use regex here
var sid = []
var matches = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17".match(/_SID_(\d+)/);
if(matches) sid.push(parseInt(matches[1]));
This solution is totally reliant on the overall string form not changing too much, ie the number of "underscores" not changing which seems fragile, props given to commenter below but he had the index wrong. My original solution first split on "SID_" since that seemed more like a key that would always be present in the string going forward.
Given:
s = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25344_SortOrder_17"
old solution:
array.push(parseInt(s.split("SID_")[1].split("_")[0]))
new solution
array.push(parseInt(s.split("_")[7])

Categories

Resources