Create Array From List of data - javascript

Hi First time Post here , please do forgive my poor English.
I have a list of data as follow
var list = '1,2,3,4,8,9,10,20,21,22,23,24'
i would like to convert this list to array, something like this
var array = ([1,4],[8,10],[20,24]);
Which it will take the first and the last(1-4) element of the list before it jump to another variable(8-10).
I have come out with some code but it's very messy
var first = true;
var firstvalue = '';
var b ='';
var endvalue ='';
var last = '';
var myArray = [];
$('.highlight').each(function() {//Loop in list
if(first){//Only For the first time to set up the loop
firstvalue = this.id;
b = firstvalue;
first = false;
return;
}
if(parseInt(this.id)-1 != b){//When gap happen and new array is insert
endvalue = b;
/*save here*/
myArray.push([firstvalue,endvalue]);
firstvalue = this.id;
b = firstvalue;
}else{
b = this.id;
}
last = this.id;//Last Item that cant capture
});
myArray.push([firstvalue,last]);
Are there any better way for this ?

Try this: easy and simple method.
var list = '1,2,3,4,8,9,10,20,21,22,23,24';
list = list.split(',');
var arrayList = [];
var firstEle = 0, lastEle = 0;
list[-1] = -2;
for(var i=-1; i<list.length; i++)
{
if(i == 0)
firstEle = list[0];
if(((list[i+1] - list[i]) > 1) && i >= 0 && i <= (list.length - 1))
{
lastEle = list[i];
arrayList.push('['+firstEle+','+lastEle+']');
firstEle = list[i+1];
}
else if(i == (list.length - 1))
{
lastEle = list[i];
arrayList.push('['+firstEle+','+lastEle+']');
}
}
alert(arrayList);

Try that:
var list = '1,2,3,4,8,9,10,20,21,22,23,24,26,27,28,30';
list = list.split(',').map(x => parseInt(x));
list.push(Infinity);
console.log(JSON.stringify(list));
var startIndex = 0;
var result = list.reduce((a, b, i, arr) => {
if(i != 0 && b - 1 != arr[i-1])
{
a.push([arr[startIndex], arr[i-1]]);
startIndex = i;
}
return a;
}, []);
console.log(JSON.stringify(result));

You could split the string and convert all values to number. Then use Array#reduce with the generated array and check the predecessor and the actual value.
If unequal with the incremented predeccessor, then concat a new array with the actual value to the result set.
Otherwise update the value at index 1 of the last array in the result set.
It works for any range sizes.
var list = '1,2,3,4,8,9,10,20,21,22,23,24',
result = list.split(',').map(Number).reduce(function (r, a, i, aa) {
if (aa[i - 1] + 1 !== a) {
return r.concat([[a]]);
}
r[r.length - 1][1] = a;
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

you can do this
var result=[];
var list = '1,2,3,4,8,9,10,20,21,22,23,24'
var dataOflist=list.split(',');
var l=dataOflist.splice(dataOflist.length-4,4);
var f=dataOflist.splice(0,4);
result[0]=f;
result[1]=dataOflist;
result[2]=l;
console.log(result);
hope this help

Related

Take a string , evaluate it and find if there is a number and repeat part of string that number of times?

I was writing code and came into this problem,
You have a specific string which is in this form:
d ae2 n s
now we have to decode this in a specific way,
Split it into different parts by spaces to make an array like ["d","ae2","n","s"]
Evaluate each element of the array and find out if there is a number in it.
If there is a number then repeat the string the number of times.
Add it into the array and continue.
So the output array should be
["d","ae","ae","n","s"]
I have already tried a lot but got nothing
I have used this code earlier but it ends on the second string:
var str = "d ae2 n s"
var res = str.split(" ");
alert(res.length);
for(var x = 0; x < res.length; x++ ){
var std = res[x];
var fun = checkNum(std);
if(fun === true){
var numbers = str.match(/\d+/g).map(Number);
var index = res.indexOf(std);
var result = std.replace(/[0-9]/g, '');
var res2 = result.repeat(numbers);
res[index] = res2;
}
else{
continue;
}
for(var i = 0; i < res.length; i++ ){
console.log(res[x]);
}
}
function checkNum(t){
return /\d/.test(t);
}
// I am a terible coder :/
expected input : d ae2 n s
expected output : ["d","ae","ae","n","s"]
Using fill() and flatMap() methods and
regex replace
/[^0-9]/ - all non numerical chars
/[0-9]/ - all numerical chars
var str = 'd ae2 n s'
var res = str
.split(' ')
.flatMap(i =>
Array(+i.replace(/[^0-9]/g, '') || 1)
.fill(i.replace(/[0-9]/g, ''))
)
console.log(res)
You can simply loop over your array and populate an other array that will hold your result after checking for a number :
const results = [];
"d ae2 n s".split(' ').forEach(token => {
const match = token.match(/\d+/);
if (match) {
const newStr = token.split(/\d/)[0];
for (let i = 0; i < match[0]; i++) {
results.push(newStr);
}
} else {
results.push(token)
}
})
console.log(results);
You can check Seblor's answer for optimized logic. I have modified your code so that it will be easy for you to understand where you went wrong while doing this. I have added comments to your code where I have changed things:
var str = "d ae2 n s"
var res = str.split(" ");
// create a variable to store the output.
var output = [];
for(var x = 0; x < res.length; x++ ){
var std = res[x];
var fun = checkNum(std);
if(fun === true){
// map returns an array, so take the first element, it will be your number.
var numbers = str.match(/\d+/g).map(Number)[0];
var index = res.indexOf(std);
var result = std.replace(/[0-9]/g, '');
// instead of doing the repeat and updating the current index,
// push the result, i.e. the current string to be repeated "numbers" times into
// the output array.
for (var i = 0; i < numbers; i++) {
output.push(result)
}
}
else{
// if does not contain any number, push the current item to ouput
output.push (std);
continue;
}
}
function checkNum(t){
return /\d/.test(t);
}
console.log(output);
You can do:
const str1 = 'd ae2 n s';
const str2 = 'e d aefg4 m n s';
const regex = /\d+/;
const getResult = input => input.split(' ').reduce((a, c) => {
const n = c.match(regex);
return n
? [...a.concat(c.replace(n, ' ').repeat(n).trim().split(' '))]
: [...a, c];
}, []);
console.log(getResult(str1));
console.log(getResult(str2));
you can use the Array prototype reduce and filter
const input = 'd ae2 n s';
const output = input.split(' ').reduce((memory, current) => {
const numberIndex = current.split('').findIndex(c => !isNaN(c));
const newCurrent = current.split('').filter((_, index) => index !== numberIndex).join('');
if(numberIndex !== -1) {
for(let i = 0; i < parseInt(current[numberIndex]); i++) {
memory.push(newCurrent);
}
} else {
memory.push(current);
}
return memory;
}, []);
console.log(output);
Hope this helped
You can try with following:
let str = "d ae2 n s"
let split = str.split(" ")
let rx = new RegExp("[0-9]")
let res = [];
split.forEach(s => {
if(rx.exec(s) !== null) {
let rxResult = rx.exec(s)
let count = rxResult[0];
let matchIdx = rxResult[1];
for(let i = 0; i < count; i++) {
res.push(s.replace(count, ""))
}
} else {
res.push(s);
}
})

Fold a multi-dimensional array n:m in JavaScript [duplicate]

I have an Array. It contains several subgroups. Example:
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
I want to divide that main array into sub-arrays.For example
sub1 =[50,51,52,53,54]
sub2 =[511,512,513,514]
sub3 =[521,522,523,524,525,526,527]
Can you help me?
Use the Array reduce function :
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
let groups = mainArray.reduce (
(grps, el, i, main) => ((el === main[i-1] + 1 ? grps[0].push (el)
: grps.unshift ([el])), grps), []);
[sub3, sub2, sub1] = groups;
console.log (sub1, sub2, sub3);
This will create an Array of Subarays:
const arr = [50,51,52,53,54, 511,512,513,514, 521,522,523,524,525,526,527];
let newArr = [];
let temp = [arr[0]];
for (let index = 1; index < arr.length; index++) {
if (arr[index] == arr[index - 1] + 1) {
temp.push(arr[index]);
} else {
newArr.push(temp);
temp = [];
}
if (index == arr.length - 1) {
newArr.push(temp);
}
}
console.log(newArr)
var arr = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
var result = [],
lastVal = -1;
while(arr.length) {
var currentIndex = arr.length - 1;
var currentValue = arr[currentIndex];
var c = Math.floor(currentValue/10);
if (c !== lastVal) {
lastVal = c;
result.push([currentValue]);
}else{
result[result.length-1].push(currentValue);
}
arr.splice(currentIndex, 1);
}
result.forEach(function(arr){ arr.reverse(); });
console.log(result);
Here's a solution using Ramda.js
const x = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
const f = R.pipe(
R.sortBy(R.identity),
R.groupWith(R.pipe(R.subtract, Math.abs, R.equals(1)))
)
console.log(f(x))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

How to separate each sub group in main group Array using javascript

I have an Array. It contains several subgroups. Example:
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
I want to divide that main array into sub-arrays.For example
sub1 =[50,51,52,53,54]
sub2 =[511,512,513,514]
sub3 =[521,522,523,524,525,526,527]
Can you help me?
Use the Array reduce function :
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
let groups = mainArray.reduce (
(grps, el, i, main) => ((el === main[i-1] + 1 ? grps[0].push (el)
: grps.unshift ([el])), grps), []);
[sub3, sub2, sub1] = groups;
console.log (sub1, sub2, sub3);
This will create an Array of Subarays:
const arr = [50,51,52,53,54, 511,512,513,514, 521,522,523,524,525,526,527];
let newArr = [];
let temp = [arr[0]];
for (let index = 1; index < arr.length; index++) {
if (arr[index] == arr[index - 1] + 1) {
temp.push(arr[index]);
} else {
newArr.push(temp);
temp = [];
}
if (index == arr.length - 1) {
newArr.push(temp);
}
}
console.log(newArr)
var arr = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
var result = [],
lastVal = -1;
while(arr.length) {
var currentIndex = arr.length - 1;
var currentValue = arr[currentIndex];
var c = Math.floor(currentValue/10);
if (c !== lastVal) {
lastVal = c;
result.push([currentValue]);
}else{
result[result.length-1].push(currentValue);
}
arr.splice(currentIndex, 1);
}
result.forEach(function(arr){ arr.reverse(); });
console.log(result);
Here's a solution using Ramda.js
const x = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
const f = R.pipe(
R.sortBy(R.identity),
R.groupWith(R.pipe(R.subtract, Math.abs, R.equals(1)))
)
console.log(f(x))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

How to find the most duplicate "values" in javascript array?

my question is actually similar to: Extracting the most duplicate value from an array in JavaScript (with jQuery)
I Found this but it always return one value only which is 200.
var arr = [100,100,200,200,200,300,300,300,400,400,400];
var counts = {}, max = 0, res;
for (var v in arr) {
counts[arr[v]] = (counts[arr[v]] || 0) + 1;
if (counts[arr[v]] > max) {
max = counts[arr[v]];
res = arr[v];
}
}
console.log(res + " occurs " + counts[res] + " times");
pls help me to return values not just one...
The result is should like this:
200,300,400
.
pls help thank you!
You have to iterate your counts to find the max occurred result.
var arr = [100,100,200,200,200,300,300,300,400,400,400];
var counts = {}, max = 0, res;
for (var v in arr) {
counts[arr[v]] = (counts[arr[v]] || 0) + 1;
if (counts[arr[v]] > max) {
max = counts[arr[v]];
res = arr[v];
}
}
var results = [];
for (var k in counts){
if (counts[k] == max){
//console.log(k + " occurs " + counts[k] + " times");
results.push(k);
}
}
console.log(results);
Create a Object iterating the arry containing the indexes of most repeated values, like below
var arr = [100,100,200,200,200,300,300,300,400,400,400];
valObj = {}, max_length = 0, rep_arr = [];
arr.forEach(function(el,i){
if(valObj.hasOwnProperty(el)){
valObj[el] += 1;
max_length = (valObj[el] > max_length) ? valObj[el] : max_length
}
else{
valObj[el] = 1;
}
});
Object.keys(valObj).forEach(function(val){
(valObj[val] >= max_length) && (rep_arr.push(val))
});
console.log(rep_arr);
After the object is created with key as array value and value as array indexes of that value, you can play/parse that. Hope this helps.
Iterating an array using for..in is not a good idea. Check this link for more information.
Hopefully below snippet will be useful
var arr = [100, 100, 200, 200, 200, 300, 300, 300, 400, 400, 400];
//Use a reduce fuction to create an object where 100,200,300
// will be keys and its value will the number of times it has
//repeated
var m = arr.reduce(function(i, v) {
if (i[v] === undefined) {
i[v] = 1
} else {
i[v] = i[v] + 1;
}
return i;
}, {});
// Now get the maximum value from that object,
//getMaxRepeated will be 3 in this case
var getMaxRepeated = Math.max(...Object.values(m));
//An array to hold elements which are repeated 'getMaxRepeated' times
var duplicateItems = [];
// now iterate that object and push the keys which are repeated
//getMaxRepeated times
for (var keys in m) {
if (m[keys] === getMaxRepeated) {
duplicateItems.push(keys)
}
}
console.log(duplicateItems)
The following would do the trick assuming that all items in arr are numbers:
//added some numbers assuming numbers are not sorted
var arr = [300,400,200,100,100,200,200,200,300,300,300,400,400,400];
var obj = arr.reduce(//reduce arr to object of: {"100":2,"200":4,"300":4,"400":4}
(o,key)=>{//key is 100,200, ... o is {"100":numberOfOccurrences,"200":numberOf...}
o[key] = (o[key])?o[key]+1:1;
return o;
},
{}
);
// obj is now: {"100":2,"200":4,"300":4,"400":4}
//create an array of [{key:100,occurs:2},{key:200,occurs:4}...
var sorted = Object.keys(obj).map(
key=>({key:parseInt(key),occurs:obj[key]})
)//sort the [{key:100,occurs:2},... by highest occurrences then lowest key
.sort(
(a,b)=>
(b.occurs-a.occurs===0)
? a.key - b.key
: b.occurs - a.occurs
);
console.log(
sorted.filter(//only the highest occurrences
item=>item.occurs===sorted[0].occurs
).map(//only the number; not the occurrences
item=>item.key
)
);
Try as following ==>
function getDuplicate( arr ){
let obj = {}, dup = [];
for(let i = 0, l = arr.length; i < l; i++){
let val = arr[i];
if( obj[val] /**[hasOwnProperty]*/ ) {
/**[is exists]*/
if(dup.find(a => a == val) ) continue;
/**[put Unique One]*/
dup.push(val);
continue;
};
/**[hold for further use]*/
obj[val] = true;
}
return dup;
};
Use ==>
getDuplicate([100,100,200,200,200,300,300,300,400,400,400]);
Try the following:
var candles = [100,100,200,200,200,300,300,300,400,400,400];
let tempArray = {}
for (let index = 0; index <= (candles.length - 1); index++) {
let valueToCompare = candles[index];
if (tempArray[valueToCompare]) {
tempArray[valueToCompare] = tempArray[valueToCompare] + 1;
} else {
tempArray[valueToCompare] = 1;
}
}
let highestValue;
Object.values(tempArray).forEach(item => {
if (highestValue === undefined) highestValue = item;
if (highestValue < item) highestValue = item;
});
console.log(highestValue);

javascript check if array contains multiple elements in a row

I would like to know if its possible to search an array for multiple items which are in a row, something similar to below. I have done it with separate includes, but this does not allow me to tell if the elements are in a row or near each other.
The array is not sorted and the numbers have to be in a defined order. Near being in a row, specifically 3. So (23,34,45) being searched within (12,23,45,34) would be false.
Thanks
var num = [];
num.push(12,23,34,45,56,67,78,89,90);
if(num.includes(23,34,45)){
print('found');
}
One more way using ES6 Set() feature:
var arr = [12,23,34,12,45,56,67,78,89,90];
var set = new Set();
arr.forEach(function(i){ set.add(i) });
var foundCount = 0;
var func = function(a){
a.forEach(function(item) {
var oldLength = set.size;
set.add(item);
var newLength = set.size;
if(oldLength === newLength) {
foundCount++;
}
});
console.log('found ' + foundCount)
}
var arr2 = [12, 34, 45];
func(arr2);
This works, I hope I understood your question correctly.
function foo(num1, num2, num3, arr) {
var exists = false;
for(var i = 0; i < arr.length; i++) {
if(arr[i] == num1 && arr[i+1] == num2 && arr[i+2] == num3) {
exists = true;
}
}
console.log(exists);
}
var array = [12,23,34,45,56,67,78,89,90];
foo(23,34,45,array);

Categories

Resources