I would like to change all elements of array (for example arr[i] +=1), but I want to do it more efficiently, without for-loop.
My for-loop implementation:
let arr = [1,2,3,4,5]
for (let i = 0; i < arr.length; i++) {
arr[i] += 1
}
console.log(arr)
// arr = [2, 3, 4, 5, 6]
In ESX using map() or reduce() methods.
Your math function:
const mathFunction = (a) => ++a
map() method
arr = arr.map(it => mathFunction(it))
reduce() method
arr = arr.reduce((acc, rec) => acc.concat(mathFunction(rec)), [])
You can use map()
let arr = [1,2,3,4,5]
arr = arr.map(x => x + 1);
console.log(arr)
Or use this:
const arrElementsPlusOne = arr.reduce((acc, nmb) => [ ...acc, nmb + 1 ], []);
You will get immutable array.
Related
I need to find the kth largest element in an array(of strings) and return them according to the rank.
Example -
Input
var array = ['java','python','javascript','C','Swift','Dart'];
Expected Output
[['javascript', 1],
['python', 2],
['Swift', 3],
['java', 4],
['Dart', 4],
['C', 5]]
I tried this -
var rank = 0
var result = []
var arr = ['java','python','javascript','C','Swift','Dart'];
arr.sort((a,b)=>b.length-a.length);
for(let i=0;i<arr.length;i++){
if(arr[i+1]===undefined){
break;
}
else if (arr[i].length>arr[i+1].length){
++rank}
result.push([arr[i],rank])
}
console.log(JSON.stringify(result))
But as you can see, it dint work. How do I approach this? A little help, please.
const arr = ['java','python','javascript','C','Swift','Dart'];
arr.sort((a, b) => b.length - a.length)
const res = arr.reduce((acc, el) => {acc.push([el, acc.length == 0 ? 1 : el.length == acc[acc.length-1][0].length ? acc[acc.length-1][1] : acc[acc.length-1][1]+1]); return acc}, [])
console.log(JSON.stringify(res))
If you want to do it your way, you can do something like the following:
let rank = 1
const arr = ['java','python','javascript','C','Swift','Dart'];
arr.sort((a,b)=>b.length-a.length);
const result = [[arr[0], 1]]
for(let i=1;i<arr.length;i++){
if (arr[i].length<arr[i-1].length){
++rank}
result.push([arr[i],rank])
}
console.log(JSON.stringify(result))
You could make use of the fact that object properties are iterated in order of index value:
const array = ['java','python','javascript','C','Swift','Dart'];
const buckets = Object.fromEntries(array.map(a => [a.length, []]));
for (let word of array) buckets[word.length].push(word);
const result = Object.values(buckets)
.reverse()
.map((bucket, rank) => bucket.map(word => [rank+1, word]))
.flat();
console.log(result);
I'm new to javascript and am trying to create a function that accepts an array of any length, and creates a new array with the rankings from that array (ie [10, 5, 20] would output [2, 3, 1]. This is my code so far ( i originally tried with a larger series of for loops finding the max each time but ran into issues getting them to repeat the same number of times as there are numbers in the array, so I switched to a sort method. Let me know if anyone can help point me in the right direction, thank you!!
function rankings(array){
let finalArray = [];
for (i = 0; i < array.length; i++) {//set up final array
finalArray[i] = array[i];
}
for(let list of array){
array.sort((a,b)=>b-a)//array sorted in order
}
for (i = array.length-1; i>=0; i--){
}
return finalArray;
}
If you like to get same ranks fro same values, cou could take the stored value for mapping.
const
rankings = array => array.map(
Map.prototype.get,
[...array]
.sort((a, b) => b - a)
.reduce((i => (m, v) => m.set(v, m.get(v) || i++))(1), new Map)
);
const result = rankings([10, 5, 20, 5]);
console.log(result);
Sort a clone (via spread) of the array, according to your ranking logic (descending in this case). Use Array.map() to create tuples of [value, index + 1], and generate a Map from the tuples.
Use Array.map() on the original array, and return the respective ranks from the Map:
function rankings(array) {
const ranks = new Map([...array].sort((a, b) => b - a)
.map((v, i) => [v, i + 1]))
return array.map(v => ranks.get(v));
}
const result = rankings([10, 5, 20]);
console.log(result);
To ignore repeat values, create a Set from the original array before spreading it:
function rankings(array) {
const ranks = new Map([...new Set(array)].sort((a, b) => b - a)
.map((v, i) => [v, i + 1]))
return array.map(v => ranks.get(v));
}
const result = rankings([10, 5, 20, 5]);
console.log(result);
You can give this a try:
var data = [10, 5, 20, 5, 4, 25];
var sorted = [...new Set([...data].sort((a,b)=>b-a))] // sorting and filtering the data
var result = data.map(elem=> getIndex = sorted.findIndex(v=>v==elem)+1);
console.log(result);
Initial code: var ar = [1,2,3,4,5,6]
I want to shift starting from second element and add last element. I try to using shift() and splice() but doesn't work and maybe something wrong on my code.
any idea to fix it?
thank you
var ar = [1,2,3,4,5,6];
ar.splice(5,1,"0").shift();
console.log(ar)
expected result [1,3,4,5,6,0]
Maybe a little slice and concat?
var ar = [1,2,3,4,5,6];
var result = ar.slice(0, 1).concat(ar.slice(2)).concat(0)
console.log(result)
Or maybe some destructuring:
const [first, , ...next] = [1,2,3,4,5,6]
console.log([first, ...next, 0])
var ar = [1,2,3,4,5,6];
ar.splice(1,1)
ar.push(0)
console.log(ar)
you can try ES6 rest operator
const array = [1,2,3,4,5]
const [firstItem, ...otherArray] = array
const newArray = [ ...otherArray, 0]
// or direct array assign
// const [firstItem, ...otherArray] = [1,2,3,4,5]
console.log(newArray)
var array = [1, 2, 3, 4, 5, 6];
function shift(arr, start, newElement) {
const arr1 = []
const rest = [];
for (let i = 0; i < start; i++) {
arr1.push(arr[i]);
}
for (let i = start + 1; i < arr.length; i++) {
rest.push(arr[i]);
}
rest.push(newElement)
return [...arr1, ...rest]
}
console.log(shift(array, 1, "0"))
console.log(shift(array, 2, "0"))
For example, if I have an array [1,2,3,4], I want to calculate 1+2, 1+2+3 and 1+2+3+4 and return a new array. How can I do that?
let arr = [1, 2, 3, 4];
doSomething(arr);
output...
newArr = [1, 3, 6, 10];
Add this function.
function dosomething (arr) {
var i;
if(i === 1 || i === 0) return arr;
for(i = 1; i<arr.length; i++){
arr[i] += arr[i-1];
}
return arr;
}
You could slice the array for getting the wanted elements and reduce the value for getting a sum.
Methods:
Array#map for getting a new array of the sum,
Array#slice returns a part of the array,
Array#reduce for adding all values.
var array = [1, 2, 3, 4],
sums = array.map((_, i, a) => a.slice(0, i + 1).reduce((a, b) => a + b));
console.log(sums);
Fun with a closure over the sum
var array = [1, 2, 3, 4],
sums = array.map((a => b => a += b)(0));
console.log(sums);
Some elegant method:
function getArrSum(arr)
{
if(!arr.length) return [];
let tmp=[arr[0]];
for(let i=1; i<arr.length; i++)
{
tmp.push(tmp[i-1]+arr[i]);
}
return tmp;
}
let arr=[1,2,3,4];
console.log(getArrSum(arr));
You can try to use array.reduce
let arr = [1, 2, 3, 4];
let newArr = [];
arr.reduce((prev, current) => {newArr.push(prev+current); return prev + current}, 0);
console.log(newArr);
Fist of all I would like to share a link which shows what should be a good question.
https://stackoverflow.com/help/how-to-ask
and about the calculation of the array is :
function getArray(numbers)
{
if(!numbers.length) return [];
let array=[numbers[0]];
for(let i=1; i < numbers.length; i++)
{
array.push(array[i-1]+numbers[i]);
}
return array;
}
let array=[1,2,3,4];
let procArray = [];
console.log(getArray(array));
var a = [1,2,3,4];
var b=[];
for(i=0;i<a.length;i++)
{
var sum = 0;
for(j=0;j<=i+1;j++)
{
if(a[j] != null)
sum=sum+a[j];
}
b[i]=sum;
}
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]); }, []);