JS delete multiple items from an array - javascript

So I have a textarea with content, only numbers and | (separators). Example :
<textarea>32|11|5|54|</textarea>
What I'd like is to append the textarea content, delete only the separators (the |) and keep the numbers, in their order. Get that kind of array :
var myArray = [22,9,54,37];
Note that I'm only allowed to basic JS
I know how to get the textarea content in a string, but I don't see how can I push() all the elements in an array, without breaking the numbers (ie having 2,2,9,5,4,3,7 instead of 22,9,54,37) AND deleting the separators. If needed I can change the separator, that's not a problem.
Pre-thanks.

Use split to split the string based on the separator.
Use .filter to remove empty values
Use .map to cast string to Number
Try this:
var val = document.getElementById('ta').value;
var arr = val.split('|').filter(function(item) {
return item; //empty string is falsey value
}).map(Number); // cast string to Number
console.log(arr);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<textarea id='ta'>32|11|5|54|</textarea>

You could use the split() function in javascript, and pass it the | as a parameter. This will create an array that contains all the numbers in order, without the | symbol.
If you need the numbers in order, then you can use the .join() with , passed in to create a string for output.
Javascript:
var textarea = document.getElementById( "textarea" ).value;
var values = textarea.split('|');
var valuesAsString = values.join(', ');
HTML:
<textarea id="textarea">32|11|5|14</textarea>

use trim in filter condition to check empty values.
try this
var res = '32|11|5|54|'.split('|').filter(function(v) {
return v.trim() != ''
})
document.write('<pre>' + JSON.stringify(res, 0, 4) + '</pre>')
res = '32|11||5|54|'.split('|').filter(function(v) {
return v.trim() != ''
})
document.write('<pre>' + JSON.stringify(res, 0, 4) + '</pre>')
res = '32|11| |5|54|'.split('|').filter(function(v) {
return v.trim() != ''
})
document.write('<pre>' + JSON.stringify(res, 0, 4) + '</pre>')

You're looking for the String.prototype.split method which accepts separator as an argument. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
So in your case it will be '22|33|44'.split('|')
If you want add these values to an existing array, you should use Array.prototype.conat method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

Related

Convert a string of array into array javascript

In my code i am reading a hidden input value which is actually a javascript array object
<input type="hidden" id="id_num" value="{{array_values}}">
But when i taking it using jquery ($('#id_num").val()) its a string of array,
"['item1','item2','item3']"
so i can not iterate it.How should i convert into javascript array object, so that i can iterate through items in the array?
You can use JSON.parse but first you need to replace all ' with " as ' are invalid delimitters in JSON strings.
var str = "['item1','item2','item3']";
str = str.replace(/'/g, '"');
var arr = JSON.parse(str);
console.log(arr);
Another approach:
Using slice and split like this:
var str = "['item1','item2','item3']";
var arr = str.slice(1, -1) // remove [ and ]
.split(',') // this could cause trouble if the strings contain commas
.map(s => s.slice(1, -1)); // remove ' and '
console.log(arr);
You can use eval command to get values from string;
eval("[0,1,2]")
will return;
[0,1,2]
more details here
Though it should be noted, if this string value comes from users, they might inject code that would cause an issue for your structure, if this string value comes only from your logic, than it is alright to utilize eval
var arr = "['item1','item2','item3']";
var res = arr.replace(/'/g, '"')
console.log(JSON.parse(res));
A possible way of solving this:
First, substr it to remove the [..]s.
Next, remove internal quotes, since we would be getting extra when we string.split
Finally, split with ,.
let mystring = "['item1','item2','item3']";
let arr = mystring.substr(1, mystring.length - 2)
.replace(/'/g, "")
.split(",")
console.log(arr)

Convert String to JSON node.js

Very new to node.js, I have string returning from RPGLE (as400) program, I would like to return as JSON example below.
String
{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},
Would like to convert as below and send to application api
[{"orderid":144234,"workorder":"996553.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"996553.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.010","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.020","shipped":1,"received":1,"status":"BAD"},
{"orderid":999290,"workorder":"999290.030","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.040","shipped":1,"received":1,"status":"GOOD"},
{"orderid":999290,"workorder":"999290.050","shipped":1,"received":1,"status":"GOOD"}]
What would be the best practice and how?
You can accomplish this string conversion through a series of regular expressions and a little decision logic to determine string and numeric values.
var meh = "{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},\
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},\
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},";
meh = "[" + // enclose with []
meh.replace(/(\w+)(?=:)/g, '"$1"') // search for words followed by a colon
.replace(/,$/, '') // trim the ending comma
.replace(/:([\w.]+)/g, function(match, value){ // grab the values
return ':' + ( // ensure preceding colon is in place
isNaN(value) || value % 1 !== 0 ? // is it a non-float number?
'"' + value + '"' : // enclose with "" if not a non-float number
parseFloat(value) // parse if is number
);
})
+ "]"; // enclose with []
console.log(JSON.parse(meh));
You could parse the lines into valid javascript objects and then stringify them into JSON like this:
const s = `
{orderid:996553,workorder:996553.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:996554,workorder:996554.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.010,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.020,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.030,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.040,shipped:000000001,received:000000001,status:GOOD},
{orderid:999290,workorder:999290.050,shipped:000000001,received:000000001,status:GOOD},
`;
const array = s.trim().split("\n").map((line) =>
line
.slice(1, -2) // remove brackets and comma
.split(",") // break into individual key/value pairs
.map((pair) => pair.split(":")) // split key/value pairs
.reduce((result, [key, value]) => { // reduce pairs into an object
result[key] = value;
return result;
},{})
);
const json = JSON.stringify(array, null, 2);
console.log(json);
How is the RPGLE program creating the string? If it is doing it piece by piece, then the RPGLE program could probably add the quotes and format the numbers correctly.

Storing The Sliced Character from .slice Method

When I utilise the slice method like so:
"Hello".slice(0,-1);
The result I get will be "Hell". Then if I run through that again using the same code, I will get "Hel".
Is there a way that I can extract and store into a variable the actual character that was sliced off, in this case "H" or on the second run "e", and not just the remainder of the string?
You could just use a second .slice() on the original string.
For example, where "Hello".slice(0,-1); returns all but the last character, "Hello".slice(-1) returns only the last character.
var input = "Hello";
var removed = input.slice(-1); // "o"
var remaining = input.slice(0, -1); // "Hell"
I don't think there's a more generic solution than that, because .slice() also lets you extract the middle of a string, in which case you'd need two extra calls to get the two parts being removed.
Demo:
var input = "Hello";
var allRemoved = [];
var removed;
while (input != "") {
allRemoved.push(removed = input.slice(-1));
input = input.slice(0, -1);
console.log("'" + removed + "' removed, leaving '" + input + "'");
}
console.log("Removed: " + allRemoved.join(", "));
Alternatively, if you only care about removing characters one at a time, you could forget about .slice() and instead convert the string to an array and use .shift() or .pop() to remove the character at the beginning or end respectively:
var input = "Hello";
var inArr = input.split("");
while (inArr.length > 0) {
console.log(inArr.pop());
}
This might not be the most efficient way to do this but you can turn yout string as an array with .split, then use .splice to remove certain elements ( letters ) and store them as a variable. Finally you turn your variable of removed letters back to a string using .join
let name = 'David'
let arrayname = name.split('')
let chosenLetters = arrayname.splice(0,2)
let finalLetters = chosenLetters.join('')
console.log(finalLetters) //should output Da
For split and join I recommend you leave the argument as (''). For .splice you can find in the docs for js how to select specific letters. In my example I am saying "Start at index 0 and cut the first 2 elements". Splice has many other ways to select an index so I recommend you read the docs.
In one line of code it can be generalized to :
let name = 'David'
let finalLetters = name.split('').splice(0,2).join('')
console.log(finalLetters) //should output Da

How remove '$' ' " ' from (["$82,549.37","$3,239.51","$39.98","$17,958.95"])

var topGls = gls.sort(function(a, b) { return a - b; });
var json = JSON.stringify(topGls);
console.log(json);
This code provides a string which is starting with $ value and " , need to remove the same characters.
Use this:
var json = '["$82,549.37","$3,239.51","$39.98","$17,958.95"]';
json = json.split('"').join('').split('$').join('');
Result:
[82,549.37,3,239.51,39.98,17,958.95]
arr=["$82,549.37","$3,239.51","$39.98","$17,958.95"]
var str=arr.join(',')
str=str.replace('$','')
arr = str.split(',')
Bear in mind this only works because you have what looks like numbers. If they were strings it may be a problem because of the join on commas.
If you want a string returned with those values all mashed together, try
json.replace(/\$|"/g, "");
//"[82,549.37,3,239.51,39.98,17,958.95]"
If you would like an array of the strings, try:
json.split('","').map(function(num){
return num.replace(/\$|\]|\[|"/g, "")
});
//["82,549.37", "3,239.51", "39.98", "17,958.95"]
Remove the commas too and add a parseFloat to get the numbers in a perhaps more useful format
json.split('","').map(function(num){
return parseFloat(num.replace(/\$|\]|\[|"|\,/g, ""))
});
//[82549.37, 3239.51, 39.98, 17958.95]

Chaining JS methods

I'm trying to insert some whitespace in a string if the string conforms to a certain format. Specifically, if the string consists of only numbers, and is exactly five characters in length, whitespace should be added between the third and fourth numbers.
Here's my test case:
function codeAddress() {
var num_regex = /^\d+$/,
input = $("#distributor-search").val(),
address = (input.match(num_regex) && input.length == 5) ? input.split('').splice(3, 0 , ' ').join() : input ;
console.log('The address is: ' + address);
return false;
}
For some reason, chaining .split(), .splice() and .join() seems to not return anything. Where am I going wrong?
split() returns an array, splice() returns the array with the removed elements and join() returns the joined array like they should.
Looks like everything goes wrong at splice(). Instead of giving the remainders, you get the removed items.
My test:
var input = '123,789';
var output = input.split(',').splice(1, 0, '456').join(',');
console.log(output); // outputs nothing, because `splice(1, 0, '456')` doesn't remove any values
You could solve this by making a prototype that uses splice's functionality, like so:
Array.prototype.isplice = function() {
var tmp = this;
Array.prototype.splice.apply(tmp, Array.prototype.isplice.arguments);
return tmp;
};
var output = input.split(',').isplice(1, 0, '456').join(',');
console.log(output); // outputs ["123", "456", "789"] as expected
As others have explained, your function didn't work because .splice() returns the removed elements, instead of the resulting array.
Try using this regex, instead:
/^(\d\d\d)(\d\d)$/
It will only match a string if it's 5 digits long, it won't modify other strings.
Examples:
var s = '123456'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123456"
var s = '1234'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "1234"
var s = '12345'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123 45"
So, in your case:
address = $("#distributor-search").val().replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
Why not just use the regex itself?
var num_regex = /^(\d\d\d)(\d\d)$/,
input = $("#distributor-search").val(),
address = input.match(num_regex);
if (address) address = address[1] + ' ' + address[2];
That regex matches a five-digit string and groups the first three and last two digits together. If the test string matches, then the .match() function returns an array with the two groups in positions 1 and 2 (position 0 being the entire match).
You can't concatenate splice with join in your case:
splice(3, 0 , ' ').join()
remember that splice returns a new array containing the removed items, not the result array.

Categories