Javascript add a break line after every other number from array - javascript

I have an array that returns some numbers like 222.000,333.000,444.000,555.000. Ideally I want to format so it places a breakline "\n" after every other number. i.e. Would be like
222.000,333.000
444.000,555.000
Can it be done by modifying the lines below?
n107 = parseFloat(output1),
n108 = parseFloat(output2),
n109 = parseFloat(output3),
n110 = parseFloat(output4),
list = [];
// add values to array if they're not NaN or > 0
if (n1) {
list.push(n1);
}
if (n2) {
list.push(n2);
}
if (n3) {
list.push(n3);
}
if (n4) {
list.push(n4);
}
if (n5) {
list.push(n5);
}
if (n6) {
list.push(n6);
}
// combine values into a string separated with commas
document.getElementById('inputTextToSave').innerHTML = list.join(",");

This is not a optimal solution.but it works
n107 = parseFloat("222.00"),
n108 = parseFloat("333.00"),
n109 = parseFloat("444.000"),
n110 = parseFloat("55.00"),
list = [n107,n108,n109,n110];
// combine values into a string separated with commas
//document.getElementById('inputTextToSave').innerHTML = list.join("</br>");
var j =1;
var htmlString = '';
for(var i =0; i< list.length; i++){
if(j<2){
htmlString += list[i]+",";
j++;
}else{
htmlString += list[i]+"</br>";
j=1;
}
}
document.getElementById('inputTextToSave').innerHTML = htmlString;
<div id="inputTextToSave"></div>

You need to create your own string in a loop instead of using join().
There are lots of ways to create the loop...the key is to check the index within the loop to determine which separator to use
var list = [222.000,333.000,444.000,555.000];
var res = list.reduce((newStr, currVal, index) =>
newStr += (index % 2 ===1 ? ',' :'\n') + currVal );
document.getElementById('inputTextToSave').innerHTML = res;
<pre id="inputTextToSave"></pre>

It can be done by using Array.reduce method.
const list = ['222.000', '333.000', '444.000', '555.000']
const result = list.reduce((memo, item, index) => {
const comma = (index+1)%2 === 0 ? ',' : ''
const lineBreak = (index+1)%2 === 0 ? '<br />' : ''
memo += comma + item + lineBreak
return memo
}, '')
document.getElementById('inputTextToSave').innerHTML = result;
<div id="inputTextToSave"></div>

you can try this function
function addBrakes(array){
let cutPoint = 3 // set where you want to cut
for(i=1; i<=array.length; i++){
if(i%cutPoint == 0){
array.splice(i, 0, "<br>")
}
}
}

Another option:
document.getElementById('inputTextToSave').innerHTML =
list.join(',').replace(/([^,]+,[^,]+),/g, '$1<br>')

Related

How can I extract all contained characters in a String? [duplicate]

I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
if the letter doesn't repeat, it's not shown (it should be)
if it's repeated once, it's show only once (i.e. aa shows a - correct)
if it's repeated twice, shows all (i.e. aaa shows aaa - should be a)
if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa - should be a)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for is inside the first.
Fill a Set with the characters and concatenate its unique entries:
function unique(str) {
return String.prototype.concat.call(...new Set(str));
}
console.log(unique('abc')); // "abc"
console.log(unique('abcabc')); // "abc"
Convert it to an array first, then use Josh Mc’s answer at How to get unique values in an array, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = Array.from(nonUnique).filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line. :-)
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Per the actual question: "if the letter doesn't repeat its not shown"
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.
Try this if duplicate characters have to be displayed once, i.e.,
for i/p: aaabbbccc o/p: abc
var str="aaabbbccc";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 ){
return obj;
}
}
).join("");
//output: "abc"
And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e.,
for i/p: aabbbkaha o/p: kh
var str="aabbbkaha";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
return obj;
}
}
).join("");
//output: "kh"
<script>
uniqueString = "";
alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");
function countChar(testString, lookFor) {
var charCounter = 0;
document.write("Looking at this string:<br>");
for (pos = 0; pos < testString.length; pos++) {
if (testString.charAt(pos) == lookFor) {
charCounter += 1;
document.write("<B>" + lookFor + "</B>");
} else
document.write(testString.charAt(pos));
}
document.write("<br><br>");
return charCounter;
}
function findNumberOfUniqueChar(testString) {
var numChar = 0,
uniqueChar = 0;
for (pos = 0; pos < testString.length; pos++) {
var newLookFor = "";
for (pos2 = 0; pos2 <= pos; pos2++) {
if (testString.charAt(pos) == testString.charAt(pos2)) {
numChar += 1;
}
}
if (numChar == 1) {
uniqueChar += 1;
uniqueString = uniqueString + " " + testString.charAt(pos)
}
numChar = 0;
}
return uniqueChar;
}
var testString = prompt("Give me a string of characters to check", "");
var lookFor = "startvalue";
while (lookFor.length > 1) {
if (lookFor != "startvalue")
alert("Please select only one character");
lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
}
document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
document.write("<br>" + uniqueString)
</script>
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
The one line solution will be to use Set. const chars = [...new Set(s.split(''))];
If you want to return values in an array, you can use this function below.
const getUniqueChar = (str) => Array.from(str)
.filter((item, index, arr) => arr.slice(index + 1).indexOf(item) === -1);
console.log(getUniqueChar("aaabbbccc"));
Alternatively, you can use the Set constructor.
const getUniqueChar = (str) => new Set(str);
console.log(getUniqueChar("aaabbbccc"));
Here is the simplest function to do that pt. 2
const showUniqChars = (text) => {
let uniqChars = "";
for (const char of text) {
if (!uniqChars.includes(char))
uniqChars += char;
}
return uniqChars;
};
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on #le_m answer
let unique=myArray.filter((item,index,array)=>array.indexOf(item)===index)

Create array based on instance of delimiter/square-brackets

I have a string and I wanna create an array with even occurrence of "[]"
"Match[0][a][5][b][0][d][2]"
I want to split them and make an array using this string on the basis of instance of "[]". Each element of the array must have 2 occurrence of "[]" and the next element has two more occurrence of"[]". In another words I wanna create an array with even occurrence of "[]"
I want to make an array from string like:
["Match[0]['a']", "Match[0]['a'][5]['b']", "Match[0]['a'][5]['b'][0]['d']"]
Using javascript/jQuery
I have tried match but I only got it as far as this.
// ['part1.abc', 'part2.abc', 'part3.abc', 'part4']
'part1.abc.part2.abc.part3.abc.part4'.match(/[^.]+(\.[^.]+)?/g);
You can get the individual pieces in your array and then manipulate the result until it has the form you want. An example could be this one:
var str = "Match[0][a][5][b][0][d][2]";
var result = [];
str.split(/[\]\[]{1,2}/).slice(0,-1).reduce(function(acc,item, index) {
acc += '[' + (isNaN(item) ? "'" + item + "'" : item) + ']';
if (index %2 === 0 && index !== 0) {
result.push(acc);
}
return acc;
});
console.log(result) // ["Match[0]['a']", "Match[0]['a'][5]['b']", "Match[0]['a'][5]['b'][0]['d']"]
You can get each bracket with match(/\[.\]/g) and then composes your arrays by adding two by two.
var matches = "Match[0][a][5][b][0][d][2]".match(/\[(.)\]/g);
var result = [];
for (var i = 0; i < matches.length; i += 2) {
var brackets = '';
for(var j = 0; j< i; j++) {
brackets += matches[j];
}
result.push("Match" + brackets);
}
result.shift();
Wow its fun :) ... trying api and see how everyone is solving it. This is what i tried see if this is helpful.
str = "STR[1][3][4d][re]"
var re=/\[\w+\]/g;
var mat = str.match(re);
var ar = [];
for(i=2; i<= mat.length; i=i+2){
ar[ar.length] = "STR" + mat.slice(0,i).join("")
}
console.dir(ar)

Each key value, join values inside loop

So i have a string, and I'm trying to join the content; if the val length is less than 10 chars, join it with the next value. But when i try this code, it joins with the same val instead of the next one.
//Set the regex.
myregex = /(<p>.*?<\/p>)/g;
//Variable string.
content = Example: <p>Hello</p><p>This is my test content</p><p>etc</p>
$(content.match(myregex)).each(function (key, val) {
var test = $(val).text();
if (test.length < 10) {
var n = val.concat(val);
$('#mydiv').append('<div>' + n + '</div>');
} else {
$('#mydiv').append('<div>' + val + '</div>');
}
})
This line here: val.concat(val), is indeed duplicating your content. What you need to do is grab the next value from the regex instead of the current one. Something like the following should work.
var matches = content.match(myregex),
myDiv = $('#mydiv');
for (var i = 0, len = matches.length; i < len; i++){
if (i + 1 < len && matches[i].length < 10){
myDiv.append('<div>' + matches[i].concat(matches[i+1]) + '</div>');
i += 1;
}
else myDiv.append('<div>' + matches[i] + '</div>');
}
val and val are the same thing, so of course val.concat(val) will duplicate it.
If you want to use $.each, I think it might be better to join with the previous value, because you don't know what the next one will be yet.
var previous = [];
$(content.match(myregex)).each(function (key, val) {
var test = $(val).text();
if (test.length < 10) {
previous = val;
} else {
if(previous.length) {
val = previous.concat(val);
}
$('#mydiv').append('<div>' + val + '</div>');
previous = [];
}
});

jQuery removing values from a comma separate list

Given an input like:
<input type="test" value="3,4,9" />
What's the best way to remove a value like 9, 4 or 3, without having issues with the commas, I don't want this ending up:
value="3,4,"
value="3,,9"
value=",4,9"
Is there a clean way to get this done in JavaScript/jQuery?
You could split your value into an array, then filter out values you do not want.
$("input[type='test']").val().split(",") // ["3","4","9"]
.filter(function(v){return !isNaN(parseInt(v))}) // filter out anything which is not 0 or more
Here is a less terse version which filters out anything which is not numeric
var array = $("input[type='test']").val().split(",");
// If you are dealing with numeric values then you will want
// to cast the string as a number
var numbers = array.map(function(v){ return parseInt(v)});
// Remove anything which is not a number
var filtered = numbers.filter(function(v){ return !isNaN(v)});
// If you want to rejoin your values
var joined = filtered.join(",");
Finally change the value on the input
$("input[type='test']").val(joined);
Similar to PHP implode/explode functions
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var explode = value.split(',');
explode.remove(1);
var implode = explode.join(',');
Documentation:
fce: Split
fce: Join
fce: Array.remove
No jQuery required :P
<script type="text/javascript">
//var subject = '3,4,9';
//var subject = '3,,9';
var subject = ',,4,9';
var clean = Array();
var i = 0;
subject = subject.split(',');
for (var a in subject)
{
if(subject[a].length)
{
clean[i] = subject[a];
i++;
}
}
document.write(clean.join(','));
</script>
You may also use pure javascript. Let say you want to take off only "4":
value = value.replace(/4,?/, '')
or "3" and "9":
value = value.replace(/([39],?)+/, '')
I think this function will work for what you are trying to do: http://www.w3schools.com/jsref/jsref_split.asp
string.split(separator, limit)
use
array = string.split(separator);
to break a string into an array. then use this to join after manipulations.
string = array.join(separator);
var ary = value.split(',');
ary.splice(indexOfItemToRemove,1)
var result = ary.join(',');
This is discussed in another post:
remove value from comma separated values string
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(",");
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(",");
}
}
return list;
}
You can use this function:
function removeComma(x) {
var str = '';
var subs = '';
for(i=1; i<=x.length; i++) {
subs = x.substring(i-1, i).trim();
if(subs !== ',') {
str = str+subs;
}
}
return str;
}

remove value from comma separated values string

I have a csv string like this "1,2,3" and want to be able to remove a desired value from it.
For example if I want to remove the value: 2, the output string should be the following:
"1,3"
I'm using the following code but seems to be ineffective.
var values = selectedvalues.split(",");
if (values.length > 0) {
for (var i = 0; i < values.length; i++) {
if (values[i] == value) {
index = i;
break;
}
}
if (index != -1) {
selectedvalues = selectedvalues.substring(0, index + 1) + selectedvalues.substring(index + 3);
}
}
else {
selectedvalues = "";
}
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(separator);
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(separator);
}
}
return list;
}
If the value you're looking for is found, it's removed, and a new comma delimited list returned. If it is not found, the old list is returned.
Thanks to Grant Wagner for pointing out my code mistake and enhancement!
John Resign (jQuery, Mozilla) has a neat article about JavaScript Array Remove which you might find useful.
function removeValue(list, value) {
return list.replace(new RegExp(",?" + value + ",?"), function(match) {
var first_comma = match.charAt(0) === ',',
second_comma;
if (first_comma &&
(second_comma = match.charAt(match.length - 1) === ',')) {
return ',';
}
return '';
});
};
alert(removeValue('1,2,3', '1')); // 2,3
alert(removeValue('1,2,3', '2')); // 1,3
alert(removeValue('1,2,3', '3')); // 1,2
values is now an array. So instead of doing the traversing yourself.
Do:
var index = values.indexOf(value);
if(index >= 0) {
values.splice(index, 1);
}
removing a single object from a given index.
hope this helps
Here are 2 possible solutions:
function removeValue(list, value) {
return list.replace(new RegExp(value + ',?'), '')
}
function removeValue(list, value) {
list = list.split(',');
list.splice(list.indexOf(value), 1);
return list.join(',');
}
removeValue('1,2,3', '2'); // "1,3"
Note that this will only remove first occurrence of a value.
Also note that Array.prototype.indexOf is not part of ECMAScript ed. 3 (it was introduced in JavaScript 1.6 - implemented in all modern implementations except JScript one - and is now codified in ES5).
// Note that if the source is not a proper CSV string, the function will return a blank string ("").
function removeCsvVal(var source, var toRemove) //source is a string of comma-seperated values,
{ //toRemove is the CSV to remove all instances of
var sourceArr = source.split(","); //Split the CSV's by commas
var toReturn = ""; //Declare the new string we're going to create
for (var i = 0; i < sourceArr.length; i++) //Check all of the elements in the array
{
if (sourceArr[i] != toRemove) //If the item is not equal
toReturn += sourceArr[i] + ","; //add it to the return string
}
return toReturn.substr(0, toReturn.length - 1); //remove trailing comma
}
To apply it too your var values:
var values = removeVsvVal(selectedvalues, "2");
guess im too slow but here is what i would do
<script language="javascript">
function Remove(value,replaceValue)
{ var result = ","+value+",";
result = result.replace(","+replaceValue+",",",");
result = result.substr(1,result.length);
result = result.substr(0,result.length-1);
alert(result);
}
Remove("1,2,3",2)
</script>
adding , before and after the string ensure that u only remove the exact string u want
function process(csv,valueToDelete) {
var tmp = ","+csv;
tmp = tmp.replace(","+valueToDelete,"");
if (tmp.substr(0,1) == ',') tmp = tmp.substr(1);
return tmp;
}
use splice, pop or shift. depending on your requirement.
You could also have "find" the indexes of items in your array that match by using a function like the one found here : http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have
var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
// 0/1/2 /3 /4/5 /6 /7 /8 /9/10/11/12/13/14/15/16/17/ 18/ 19/ 20
var thirty=tmp.find(30); // Returns 9, 14, 17
var thirtyfive=tmp.find('35'); // Returns 18
var thirtyfive=tmp.find(35); // Returns 15
var haveBlue=tmp.find('blue'); // Returns 8
var notFound=tmp.find('not there!'); // Returns false
var regexp1=tmp.find(/^b/); // returns 8,20 (first letter starts with b)
var regexp1=tmp.find(/^b/i); // returns 8,19,20 (same as above but ignore case)
Array.prototype.find = function(searchStr) {
var returnArray = false;
for (i=0; i<this.length; i++) {
if (typeof(searchStr) == 'function') {
if (searchStr.test(this[i])) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
} else {
if (this[i]===searchStr) {
if (!returnArray) { returnArray = [] }
returnArray.push(i);
}
}
}
return returnArray;
}
or
var csv_remove_val = function(s, val, sep) {
var sep = sep || ",", a = s.split(sep), val = ""+val, pos;
while ((pos = a.indexOf(val)) >= 0) a.splice(pos, 1);
return a.join(sep);
}

Categories

Resources