I have strings like this :
"831,403,746,399,745,409,752,426,764,435,775,448,781,467,780,483,776,509,826,513"
"832,402,917,408,915,422,910,432,904,437,894,443,885,450,878,462,876,475,874,491,874,516,825,511"
"468,297.00000762939453,434,218.00000762939453,416,230.00000762939453,409,246.00000762939453,405,264.00000762939453,400,275.00000762939453,384,282.00000762939453,374,288.00000762939453,352,297.00000762939453,369,340.00000762939453"
... and so on.
I need to format the strings and produce arrays in array like this :
E.g.:
var myArray = [
[831,403],
[746,399],
[745,409],
[752,426],
[764,435],
[775,448],
[781,467],
[780,483],
[776,509],
[826,513],
];
It is possible and how?
Thanks in advance!
function parseToMatrix(str, rowCount = 2) {
let numbers_array = str.split(",").map((str) => parseFloat(str));
let matrix = [];
for (let i = 0; i < numbers_array.length; i += rowCount) {
matrix.push(numbers_array.slice(i, i + rowCount));
}
return matrix;
}
let str =
"831,403,746,399,745,409,752,426,764,435,775,448,781,467,780,483,776,509,826,513";
console.log(parseToMatrix(str));
Related
I have a variable (for example):
var numINeed = 4
I need to dynamically create an array like so:
var arrayINeed = ["value_1","value_2","value_3","value_4"]
Where the last item is formatted such that the # in value_# is equal to var numINeed, meaning that the length of arrayINeed = length of var numINeed
Attempted so far:
I've attempted to create the array using a for loop (I'm using Vue JS by the way)
data: () => ({
arrayINeed: [],
variableA: []
}),
for (var i = 0; i<this.numINeed; ++i) {
this.variableA = "value_" + i;
this.arrayINeed.push(this.variableA);
}
I believe this might be written wrongly. How might I be able to make it work as intended?
using ES6:
let arrayINeed = Array.from(Array(4), (_,x) => "value_" + (x+1));
console.log(arrayINeed);
I just edited your code. Variable i is starting from zero, So I added one to it.
var numINeed = 4;
arrayINeed = [];
for (var i = 0; i<numINeed; ++i) {
let variableA = "value_" + (i+1);
arrayINeed.push(variableA);
}
console.log(arrayINeed);
A short code could be this:
var numINeed = 4;
var newArray = Array(numINeed).fill('').map((v, i) => `value_${i+1}`);
console.log(newArray);
Generate array using while loop
var numINeed = 4;
var arrayINeed = [];
var i = 1;
while (i < numINeed + 1) {
arrayINeed.push("value_" + i);
i++;
}
console.log(arrayINeed);
How to count the JSON object and on the basis of count take the same output
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
First I would like the count after it on the basis of count. I want same output like input.
for Count:-
var count = 0;
function getCount() {
for (var i = 0; i < obj.length; i++) {
count++;
}
return count;
}
for output :-
function showDetails() this is not giving the proper output
{
for(var j=0; j< count; j++){
obj.push([{j}]);
}
alert(obj.name);
}
alert(showDetails());
And I want an output like:-
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
Can anybody help me please?
var data ="January,February,March,April,May,June,July,August,September,October";
var obj = data.split(',').map((item)=>{
return {
name:item
}
});
obj will be the desired output
var str = "January,February,March,April,May,June,July,August,September,October";
var arr = str.split(',').map(function(v) {
return {name: v};
});
console.log(arr);
var str = "January,February,March,April,May,June,July,August,September,October";
var months = str.split(",");
var result = [];
for (i in months)
{
var month = {};
month.name = months[i];
//you can do more things else here, for example:
//month.monthOfYear = (i+1);
//month.numberOfDay = 123123123;
result.push(month);
}
You can do something like this:
var array = string.split(",");
var finalArray = [];
array.forEach(function(item){
var obj = {
name: item
}
finalArray.push(obj);
});
console.log(finalArray);
MDN reference
use var array = string.split(',');
For a more ES2015 heavy version. Constants, arrow function and implicit return statement.
const str = 'January,February,March,April,May,June,July,August,September,October'
const result = str.split(',').map(name => ({name}))
console.log(result)
I have a string in javascript where there are a lot of duplicates. For example I have:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
What can I do to delete duplicates and to get for example x="Int32,Double"?
With Set and Array.from this is pretty easy:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
If you have to support current browsers, you can split the array and then filter it
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
Use new js syntax remove Dupicate from a string.
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
function myFunction(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result = result+char;
}
}
return result;
}
That is a more readable and better parameterized solution:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//result "Int32,Double"
Check This out -
removeDuplicates() function takes a string as an argument and then the string split function which is an inbuilt function splits it into an array of single characters. Then the arr2 array which is empty at beginning, a forEach loop checks for every element in the arr2 - if the arr2 has the element it will not push the character in it, otherwise it will push. So the final array returned is with unique elements. Finally we join the array with the join() method to make it a string.
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
Its simple just remove duplicates in string using new Set and join them.
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
You can use Set()
const result = Array.from(new Set(x)).join('')
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
const result = Array.from(new Set(x)).join('')
console.log(result)
you can use the replaceAll function:
let str = "/Courses/"
let newStr = str.replaceAll('/', '')
console.log(newStr) // result -> Courses
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
STEPS
convert string to character array using spread operator
new Set will implicitly remove duplicate character
convert character array to string using join("") method
I have the following array:
var mystr = "Name[Daniel],Name2[Alguien],Date[2009],Date[2014]";
How can I convert it to an array like this:
var array = ['Daniel','Alguien','2009',2014];
You can do it this way:
var mystr = "Name[Daniel],Name2[Alguien],Date[2009],Date[2014]";
var array = mystr.match(/\[.+?\]/g).map(function(value){ // searches for values in []
return value.replace(/[\[\]]/g,""); // removes []
});
Try to use following code , as you can see the string is split by comma and then using regular expressions the necessary part has been pushed to new array
var mystr = "Name[Daniel],Name2[Alguien],Date[2009],Date[2014]";
var array = mystr.split(",");
re = /\[(.*)\]/;
var newArray = [];
for (var i = 0; i < array.length; i++) {
newArray.push(array[i].match(re)[1]);
}
newArray = ['Daniel', 'Alguien', '2009', 2014];
If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);