How to take an array, and insert commas between each item? - javascript

I am trying to understand how to take an array like [1,2,3,4,5] and then between each index, add a , so the array becomes [1, ', ', 2, ', ', 3, ', ', 4, ', ', 5]
I know it sounds stupid but I'm having some issues with it.
Basically, I want to use something like splice() method, so that I can iterate over the array and each odd index, I can do splice(index, 0, ', ').

You can use .reduce method which accepts as parameter a callback function.
The reduce() method applies a function against an accumulator and each
value of the array (from left-to-right) to reduce it to a single
value.
var array=[1,2,3,4,5];
console.log(array.reduce(function(a,b){
return a.concat(b).concat(",");
},[]).slice(0,-1));

Use .reduce()
Start with empty array
Push an element of array then push ', '
At last remove last ', ' using .pop()
var array1 = [1, 2, 3, 4, 5]
var array2 = array1.reduce(function(acc, val) {
acc.push(val);
acc.push(', ');
return acc;
}, []);
array2.pop();
console.log(array2);

You can use reduce to create a new array with the inserted values:
function weaveArray(array, weaveValue) {
const {length} = array;
return array.reduce((result, value, i) => {
if(i < length - 1) {
result.push(value, weaveValue);
} else {
result.push(value);
}
return result;
}, []);
}
console.log(
weaveArray([1,2,3,4,5], ",")
);

console.log([1,2,3,4,5].reduce(function(acc, val, idx, list) {
acc.push(val);
if (idx < list.length - 1) {
acc.push(',');
}
return acc;
}, []));

With just two methods:
Edit
If you want to save your commas use some regexp instead:
var c = a.join(', , , ').split(/\s(?=,\s)/);
var a = [1,2,3,4,5];
var b = a.join(' , ').split(' ');
var c = a.join(', , , ').split(/\s(?=,\s)/);
console.log(b,c);

Short solution using Array.prototype.join(), Array.prototype.map() and String.prototype.match() functions:
var arr = [1,2,3,4,5],
newArr = arr.join(',').match(/\w+|\W+/g).map(function(v){
return (isNaN(v))? v : +v; // considering numeric values
});
console.log(newArr);
You wanted splice approach? Here it is:
var arr = [1,2,3,4,5];
for (var i = 1; i < arr.length; i+=2) {
arr.splice(i, 0, ',');
}
console.log(arr);

You can use a variable at .splice() to increment index by 2
var arr = [1,2,3,4,5];
for (let i = 1, len = arr.length * 2; arr.length < len - 1; arr.splice(i, 0, ","), i += 2);
console.log(arr);

Related

How to join array elements in pairs in javascript

I have a array of numbers [1,2,3,4,5,6,7,8,9,10] and I want to make it into a string like this: '1,2 3,4 5,6 7,8 9,10'. Is there some fast and simple vay to do this in javascript or do i have to use the loop?
for(let i = 0; i < array.length; i++){
if(i%2 == 0){
res += array[i] + ',';
} else {
res += array[i] + ' ';
}
}
You can use reduce to get the result you desire:
[1,2,3,4,5,6,7,8,9,10]
.reduce((acc, val, idx) =>
idx % 2 === 0
? (acc ? `${acc} ${val}` : `${val}`)
: `${acc},${val}`, '')
// "1,2 3,4 5,6 7,8 9,10"
By taking advantage of the third parameter of the reduce function we know the index of the element we are currently iterating over, therefore also making this function work for arrays that aren't numbers 1 through 10.
You could get pairs with comma and then join the array with spaces for the string, but you need still a loop
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
temp = [],
i = 0,
string;
while (i < array.length) {
temp.push(array.slice(i, i += 2).join());
}
string = temp.join(' ');
console.log(string);
You could chunk the array, and join the elements with commas and spaces:
var arr = [1,2,3,4,5,6,7,8,9,10,11]
chunkArr = arr.reduce((acc, item, index) => {
const i = Math.floor(index/2)
if(!acc[i]) {
acc[i] = []
}
acc[i].push(item)
return acc
}, [])
arr = chunkArr.map(arr => arr.join(',')).join(' ')
console.log(arr)
Note, this code works with an odd amount of numbers too.

How to get value from an array, only those what is greater than all elements to its right

I wanted to write a function to get all numbers, what is greater than all elements to its right.
Example if i have an array like this:
arr = [ 75,47,42,56,13,55];
I want a result like this [75,56,55]in a new array.
Other example if i have an array like this:
arr = [16,17,14,3,14,5,2]
I want a result like: [17,14,5,2]
What methods can i use to get this result whatever numbers i have in an array?
You can use filter the array. splice the array to get all the numbers on the right. Use every to check if all array elements are greater than the value.
let arr = [75, 47, 42, 56, 13, 55];
let result = arr.filter((v, i, a) => [...a].splice(i + 1, a.length).every(o => v > o));
console.log(result);
Doc: filter(), splice(), every()
You could simply iterate from the right side and check against the latest found greatest value.
function greaterThanRight(array) {
return array.reduceRight((r, v) => [].concat(v <= r[0] ? [] : v, r), [])
}
console.log([[75, 47, 42, 56, 13, 55], [16, 17, 14, 3, 14, 5, 2]].map(greaterThanRight).map(a => a.join(' ')));
A simple for loop where inner loop has index starting with the index value of the match having highest right value:
var arr = [ 75,47,42,56,13,55];
var res = [];
for(var i=0; i<arr.length; i++){
var highestValue = arr[i];
for(var j=i+1; j<arr.length; j++){
if(highestValue < arr[j]){
highestValue = arr[j];
i = j;
break;
}
}
res.push(highestValue);
}
console.log(res);
var arr = [75,47,42,56,13,55];
arr.sort(function(a, b) {
// a = current item in array
// b = next item in array
return b - a;
});
var newArr = arr.slice(0,3);
console.log(newArr);
Try this. Just start checking from the right.keep a variable max and update it whenever you found a new max
var arr = [ 75,47,42,56,13,55];
function findMaxRight(arr){
var res=[]
var max = Number.MIN_SAFE_INTEGER
for(var i=arr.length -1; i>=0;i--){
if(arr[i]> max){
res.unshift(arr[i])
max = arr[i]
}
}
return res
}
console.log(findMaxRight(arr));
One way to do it could be to loop your array, get the current item and get the rest of the array after the current item using slice.
Then sort the rest of the array descending and get the first entry which is the highest one.
If the current value is larger than the highest one, it is larger then all the values on the right:
let items = [75, 47, 42, 56, 13, 55];
let result = [];
items.forEach((item, index) => {
let head = items[index];
let tail = items.slice(index + 1).sort(function(a, b) {
return b - a;
});
if ((head > tail[0]) || (index === items.length - 1)) {
result.push(head);
}
});
console.log(result);
My solution to do this : find the max and if it's the current number store it, continue with the new array looping = looping.slice(1)
let arr = [75,47,42,56,13,55];
let looping = [...arr];
let finish = arr.reduce( (acc, x) => {
if(x === Math.max(...looping)) acc.push(x);
looping = looping.slice(1);
return acc;
}, [])
console.log(finish) // [75,56,55]

Is there a simpler way to create a sum of previous values in an array?

I'm basically looking for a simpler way to do this:
heights.forEach((height, i) => {
var p = i > 0 ? i -1 : 0;
this.breakingPoints.push(height+heights[p])
})
If I input an array that is:
[0,2,5,5]
I would like to output
[0,2,7,12]
You could use map() method with closure to return new array.
const arr = [0,2,5,5];
const result = (s => arr.map(e => s += e))(0);
console.log(result)
You can simply store the variable to push in a variable which will allow you to automatically sum the new value to it without checking the index.
var total = 0;
heights.forEach(height => {
this.breakingPoints.push(total += height);
})
The result would be:
[0, 2, 7, 12]
You can use Array.reduce method.
let inputArray = [1, 2, 3, 4];
let outputArray = [];
inputArray.reduce(function(accumulator, currentValue, currentIndex) {
return outputArray[currentIndex] = accumulator + currentValue; }, 0);
You could use reduce and spread operator to concat values:
const input = [0, 2, 5, 5];
const output = input.reduce((acc, val) => [...acc, (acc[acc.length - 1] ? acc[acc.length - 1] : 0) + val],[]);
Or when using < ES6
var output = input.reduce(function (acc, val) { return acc.concat([(acc[acc.length - 1] ? acc[acc.length - 1] : 0) + val]); }, []);

Sort an array and store its indices in another array in javascript

I have an array like array = [9,0,0,1,0,5,1,3,1] . I want to sort this array and get the indices of the sorted array elements as another array.
ie. after sorting:
sortedArray = [0,0,0,1,1,1,3,5,9]
indexArray = [1,2,4,3,6,8,7,5,0]
Is there any way to get the indices of the sorted array?
You can try something like this:
(function() {
var arr = [9, 0, 0, 1, 0, 5, 1, 3, 1];
var _temp = arr.map(function(item, index) {
return {
index: index,
value: item
}
});
console.log(_temp)
_temp.sort(function(a, b) {
if (a.value < b.value) return -1;
if (a.value > b.value) return 1;
return 0;
});
console.log(_temp)
console.log(_temp.map(function(item) {
return item.value
}))
console.log(_temp.map(function(item) {
return item.index
}))
})()
Since there's no index-value association in an array, you'll need to establish that first:
var tmp = array.map(function (val, i) { return [i, val]; });
// [[0, 9], [1, 0], ..]
Then you sort it:
tmp.sort(function (a, b) { return a[1] - b[1]; });
Then you extract the indices and/or values again:
var indexArray = tmp.map(function (i) { return i[0]; });
Something like this?
var array = [9,0,0,1,0,5,1,3,1];
var indexArray = [];
for (var i = 0; i < array.length; ++i) {
indexArray.push(i);
}
var sortedArray = array.sort();
console.log(sortedArray);
console.log(indexArray);
Having the sortedArray, you can loop over the array, and use the indexOf() Method to get the index of the each element of the sorted array in the old array. For example.
sortedArray.forEach(function(ele){
indexArray.push(oldArray.indexOf(ele));
});

How to search for multiple index(es) of same values in javascript array

I have a 1 dimensional array like:
var abc = ['a','a','b','a','c']
Now I want to get back all the indexes of 'a', that is 0, 1 and 3.
Are there any simple solutions?
P.S.
I know IndexOf or jQuery.inArray(). But they just returned the index of first matched element only
You could extend the basic Array Object with the following method:
Array.prototype.multiIndexOf = function (el) {
var idxs = [];
for (var i = this.length - 1; i >= 0; i--) {
if (this[i] === el) {
idxs.unshift(i);
}
}
return idxs;
};
Then the operation
var abc = ['a','a','b','a','c'];
abc.multiIndexOf('a');
would give you the result:
[0, 1, 3]
Jsperf comparison of unshift / push / push(reverse order)
You could use Array#reduce with Array#concat with a check for the wanted item, take the index or an empty array.
var abc = ['a', 'a', 'b', 'a', 'c'],
indices = abc.reduce((r, v, i) => r.concat(v === 'a' ? i : []), []);
console.log(indices);
ES5
var abc = ['a', 'a', 'b', 'a', 'c'],
indices = abc.reduce(function (r, v, i) {
return r.concat(v === 'a' ? i : []);
}, []);
console.log(indices);
Rather than using a for loop, you can use a while loop combined with indexOf:
var array = [1, 2, 3, 4, 2, 8, 5],
value = 2,
i = -1,
indizes = [];
while((i = array.indexOf(value, i + 1)) !== -1) {
indizes.push(i);
}
This will return you [1, 4] and of course could be combined with extending the prototype of Array.
The second argument of indexOf specifies where to start the search in the given array.
You can take advantage of the fact that $.map() does not push values in its resulting array when the function you pass returns undefined.
Therefore, you can write:
var abc = ["a", "a", "b", "a", "c"];
var indices = $.map(abc, function(element, index) {
if (element == "a") {
return index;
}
});
You also use reduce function on the array and push the indexes to accumulated array, you need start with an empty array, the good thing about reduce is it's async and also time execution is faster than for loop, also it's a native function on array, look at the below, hope it's helping:
var arr = [0, 1, 2, 3, 7, 2, 3, 4, 7, 8, 9, 2, 3];
function indexesOf(num) {
var reduced = arr.reduce(function(acc, val, ind, arr){
if(val === num){
acc.push(ind);
}
return acc;
}, []);
return reduced;
}
indexesOf(2); //[2, 5, 11]
AFAIK, there's no Javascript or jQuery function that does this in one step, you have to write a loop.
var indexes = [];
$.each(abc, function(i, val) {
if (val == "a") {
indexes.push(i);
}
}
Do it this way :
var abc = ['a','a','b','a','c'];
for (var i=0; i<abc.length; i++) {if(abc[i]=='a') {console.log(i)};}
If your array size is fixed, then you can find the first occurrence in the array using indexOf(). Use the found index value as starting point in indexOf() to find an other occurrence.
var firstOccurance = [your_array].indexOf(2)
var secondOccurance = [your_array].indexOf(2, firstOccurance + 1)
Demo
use for loop
var arr = ['a', 'a', 'b', 'a', 'c'];
var indexA = [];
for (var i = 0; i < arr.length; i++) {
if ("a" == arr[i]) indexA.push(i)
}
With ES6 syntax you could go with forEach and the ternary operator :
const abc = ['a','a','b','a','c']
let matchingIndexes = []
abc.forEach( (currentItem, index) => {
currentItem === 'a' ? matchingIndexes.push(index) : null
})
console.log(matchingIndexes) // [0, 1, 3]

Categories