How to split string by rows and column in Javascript - javascript

I have an below string with two delimeter."|" is used for rows and "*" is used for columns.I would like to know how to split these string by rows and column in JS Code
"1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|"

You could use the split function twice to create nested array:
let str = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|";
let arr = str.split("|").map(r => r.split("*"));
console.log(arr);

You can split with multiple delemiter with.
const str = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|"
const splitStr = str.split(/\*|\|/);
console.log(splitStr);

const input = "1264.75|24936.00|38230.76|48329.75|53106.25|63442.00|75122.50|1077.00|117581.00|127573.25|133509.00|215246.50|244181.00|254961.25|52*34.00|"
// The filter is for removing empty rows
input.split("|").filter(val=>!!val).map(val => val.split("*").map(res=>parseFloat(res)))
The result will be like
[[1264.75],[24936],[38230.76],[48329.75],[53106.25],[63442],[75122.5],[1077],[117581],[127573.25],[133509],[215246.5],[244181],[254961.25],[52,34]]

Plenty of good answers here already - this returns as an array of cell objects with row/column attributes:
let mystring = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|";
let cells = mystring.split("|");
let results = [];
for (let i = 0; i < cells.length; i++) {
let cell = cells[i];
let cellData = cell.split("*");
results.push({
row: cellData[0],
col: cellData[1]
})
}
console.log(results);

If you want to go over it in one pass, this should create a nested array structure representing arrays / columns. It is also very rough and can likely be simplified a bit.
const fullStr = "1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00|21*5246.50|24*4181.00|25*4961.25|52*34.00|";
const arr = [[]];
for(let i = 0, str = ''; i < fullStr.length; i++){
if(fullStr[i] == '*') {
arr[arr.length - 1].push(str);
str = '';
continue;
}
if(fullStr[i] == '|') {
arr[arr.length -1].push(str);
// you could wrap this push statement in an if to determine if you are at the end of the string.
arr.push([]);
str = '';
continue;
}
str += fullStr[i];
}
console.log(arr);

Maybe a little old-fashioned but works just as well
var a ="1*264.75|2*4936.00|3*8230.76|4*8329.75|5*3106.25|6*3442.00|7*5122.50|10*77.00|11*7581.00|12*7573.25|13*3509.00";
var b = a.split("|");
var c = [];
for (i = 0; i < b.length; i++) {
c[i] = b[i].split("*");
}

Related

Common Character Count in Strings JavaScript

Here is the problem:
Given two strings, find the number of common characters between them.
For s1 = "aabcc" and s2 = "adcaa", the output should be 3.
I have written this code :
function commonCharacterCount(s1, s2) {
var count = 0;
var str = "";
for (var i = 0; i < s1.length; i++) {
if (s2.indexOf(s1[i]) > -1 && str.indexOf(s1[i]) == -1) {
count++;
str.concat(s1[i])
}
}
return count;
}
console.log(commonCharacterCount("aabcc", "adcaa"));
It doesn't give the right answer, I wanna know where I am wrong?
There are other more efficient answers, but this answer is easier to understand. This loops through the first string, and checks if the second string contains that value. If it does, count increases and that element from s2 is removed to prevent duplicates.
function commonCharacterCount(s1, s2) {
var count = 0;
s1 = Array.from(s1);
s2 = Array.from(s2);
s1.forEach(e => {
if (s2.includes(e)) {
count++;
s2.splice(s2.indexOf(e), 1);
}
});
return count;
}
console.log(commonCharacterCount("aabcc", "adcaa"));
You can do that in following steps:
Create a function that return an object. With keys as letters and count as values
Get that count object of your both strings in the main function
Iterate through any of the object using for..in
Check other object have the key of first object.
If it have add the least one to count using Math.min()
let s1 = "aabcc"
let s2 = "adcaa"
function countChars(arr){
let obj = {};
arr.forEach(i => obj[i] ? obj[i]++ : obj[i] = 1);
return obj;
}
function common([...s1],[...s2]){
s1 = countChars(s1);
s2 = countChars(s2);
let count = 0;
for(let key in s1){
if(s2[key]) count += Math.min(s1[key],s2[key]);
}
return count
}
console.log(common(s1,s2))
After posting the question, i found that i havent looked the example well. i thought it wants unique common characters ..
and i changed it and now its right
function commonCharacterCount(s1, s2) {
var count = 0;
var str="";
for(var i=0; i<s1.length ; i++){
if(s2.indexOf(s1[i])>-1){
count++;
s2=s2.replace(s1[i],'');
}
}
return count;
}
Create 2 objects containing characters and their count for strings s1
and s2
Count the common keys in 2 objects and return count - Sum the common keys with minimum count in two strings
O(n) - time and O(n) - space complexities
function commonCharacterCount(s1, s2) {
let obj1 = {}
let obj2 = {}
for(let char of s1){
if(!obj1[char]) {
obj1[char] = 1
} else
obj1[char]++
}
for(let char of s2){
if(!obj2[char]) {
obj2[char] = 1
} else
obj2[char]++
}
console.log(obj1,obj2)
let count = 0
for(let key in obj1 ){
if(obj2[key])
count += Math.min(obj1[key],obj2[key])
}
return count
}
I think it would be a easier way to understand. :)
function commonCharacterCount(s1: string, s2: string): number {
let vs1 = [];
let vs2 = [];
let counter = 0;
vs1 = Array.from(s1);
vs2 = Array.from(s2);
vs1.sort();
vs2.sort();
let match_char = [];
for(let i = 0; i < vs1.length; i++){
for(let j = 0; j < vs2.length; j++){
if(vs1[i] == vs2[j]){
match_char.push(vs1[i]);
vs2.splice(j, 1);
break;
}
}
}
return match_char.length;
}
JavaScript ES6 clean solution. Use for...of loop and includes method.
var commonCharacterCount = (s1, s2) => {
const result = [];
const reference = [...s1];
let str = s2;
for (const letter of reference) {
if (str.includes(letter)) {
result.push(letter);
str = str.replace(letter, '');
}
}
// ['a', 'a', 'c'];
return result.length;
};
// Test:
console.log(commonCharacterCount('aabcc', 'adcaa'));
console.log(commonCharacterCount('abcd', 'aad'));
console.log(commonCharacterCount('geeksforgeeks', 'platformforgeeks'));
Cause .concat does not mutate the string called on, but it returns a new one, do:
str = str.concat(s1[i]);
or just
str += s1[i];
You can store the frequencies of each of the characters and go over this map (char->frequency) and find the common ones.
function common(a, b) {
const m1 = {};
const m2 = {};
let count = 0;
for (const c of a) m1[c] = m1[c] ? m1[c]+1 : 1;
for (const c of b) m2[c] = m2[c] ? m2[c]+1 : 1;
for (const c of Object.keys(m1)) if (m2[c]) count += Math.min(m1[c], m2[c]);
return count;
}

Writing a function that returns different combinations of letters

I was going through some challenges and I need some help to solve this one . I should write function permutations(string) that returns an array of all permutations of the given string .
permutations('a'); // ['a']
permutations('ab'); // ['ab', 'ba']
permutations('aabb'); // ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa']
let permutation = str => {
let array = [...str];
let resultado = [];
for(let i = 0; i< array.length; i++){
let temp = array.filter((q,c,y)=> c != i);
for(x = 0; x < array.length; x++)
{
let temp2 = temp.slice(0);
temp2.splice(x,0,array[i]);
resultado.push(temp2);
}
}
return [...new Set(resultado.map(item => item.join('')))]
}
console.log(permutation('abbb'));
That is the long form. It would have to work more than reduce the size of the code.

Creating an array without hard-coding

I'm trying to create an array of strings and produce the possibilities by the length of array string. For example:
var someStr = ["a","b","c","d"];
//I want to produce this outcome
a
ab
abc
abcd
b
bc
bcd
c
cd
d
I know I can get the # of possibilities for "a" only by this way:
var numCombinations = 0;
var comboString = '';
var outcome = [];
for(var i = 0; i < someStr.length; i++){
comboString += someStr[i];
outcome[i] = comboString;
numCombinations += i; //# of combinations from above
}
But how would I continue with these variables for the left over possibilities? I've thought of creating nested for-loops again and again but that would eventually lead to the (n)th length with hard-coding. Would there be any method(s) to create this and store all the possibilities to the (n)th length?
Hope this help.
function getComboStringListFromIdx(arr, idx){
var result = [];
var comboString = '';
for(var i=idx; i<arr.length; i++){
comboString += arr[i];
result.push(comboString);
}
return result;
}
var someStr = ['a','b','c','d'];
var outCome = [];
for(var i = 0; i<someStr.length; i++){
outCome = outCome.concat(getComboStringListFromIdx(someStr, i));
}
I will also use nested for-loop ! One is normal looping and other is to skip less than current index from first loop !!
var someStr = ["a","b","c","d"];
for(var i = 0;i < someStr.length;i++) {
output(i);
}
function output(index) {
var str = "";
for(var j in someStr) {
if(j < index) {
continue;
}
str += someStr[j];
console.log(str);
}
}
This solution uses a nested for loop and skips concatenation on the first element of the nested for loop.
var arr = ["a","b","c","d"];
for(var i=0;i<arr.length;i++){
var str = arr[i];
for(var j=i;j<arr.length;j++){
if(i!==j)
str+=arr[j];
console.log(str);
}
}
https://jsfiddle.net/fmy539tj/

Explode and process values as an array using Javascript [duplicate]

So, I have a string with the delimiter | , one of the sections contains "123", is there a way to find this section and print the contents?
something like PHP explode (but Javascript) and then a loop to find '123' maybe? :/
const string = "123|34|23|2342|234";
const arr = string.split('|');
for(let i in arr){
if(arr[i] == 123) alert(arr[i]);
}
Or:
for(let i in arr){
if(arr[i].indexOf('123') > -1) alert(arr[i]);
}
Or:
arr.forEach((el, i, arr) => if(arr[i].indexOf('123') > -1) alert(arr[i]) }
Or:
arr.forEach((el, i, arr) => if(el == '123') alert(arr[i]) }
Or:
const arr = "123|34|23|2342|234".split('|')
if(arr.some(el=>el == "123")) alert('123')
More information on string and Array memeber functions.
You can use split() in JavaScript:
var txt = "123|1203|3123|1223|1523|1243|123",
list = txt.split("|");
console.log(list);
for(var i=0; i<list.length; i++){
(list[i]==123) && (console.log("Found: "+i)); //This gets its place
}
LIVE DEMO: http://jsfiddle.net/DerekL/LQRRB/
This should do it:
var myString = "asd|3t6|2gj|123hhh", splitted = myString.split("|"), i;
for(i = 0; i < splitted.length; i++){ // You could use the 'in' operator, too
if(splitted[i].match("123")){
// Do something
alert(splitted[i]); // Alerts the entire contents between the original |'s
// In this case, it will alert "123hhh".
}
}
.split is the equivalent of explode, whereas .join is the equivalent of implode.
var myString = 'red,green,blue';
var myArray = myString.split(','); //explode
var section = myArray[1];
var myString2 = myArray.join(';'); //implode

How to create an array like this in JavaScript?

I want to create an array like this:
s1 = [[[2011-12-02, 3],[2011-12-05,3],[5,13.1],[2011-12-07,2]]];
How to create it using a for loop? I have another array that contains the values as
2011-12-02,3,2011-12-05,3,2011-12-07,2
One of possible solutions:
var input = ['2011-12-02',3,'2011-12-05',3,'2011-12-07',2]
//or: var input = '2011-12-02,3,2011-12-05,3,2011-12-07,2'.split(",");
var output = [];
for(i = 0; i < input.length; i += 2) {
output.push([t[i], t[i + 1]])
}
If your values always come in pairs:
var str = '2011-12-02,3,2011-12-05,3,2011-12-07,2',//if you start with a string then you can split it into an array by the commas
arr = str.split(','),
len = arr.length,
out = [];
for (var i = 0; i < len; i+=2) {
out.push([[arr[i]], arr[(i + 1)]]);
}
The out variable is an array in the format you requested.
Here is a jsfiddle: http://jsfiddle.net/Hj6Eh/
var s1 = [];
for (x = 0, y = something.length; x < y; x++) {
var arr = [];
arr[0] = something[x].date;
arr[1] = something[x].otherVal;
s1.push(arr);
}
I've guessed here that the date and the other numerical value are properties of some other object, but that needn't be the case...
I think you want to create an array which holds a set of arrays.
var myArray = [];
for(var i=0; i<100;i++){
myArray.push([2011-12-02, 3]); // The values inside push should be dynamic as per your requirement
}

Categories