I have an object in javascript like this:
{ "a":4, "b":0.5 , "c":0.35, "d":5 }
Is there a fast way to get the minimum and maximum value among the properties without having to loop through them all? because the object I have is huge and I need to get the min/max value every two seconds. (The values of the object keeps changing).
Update: Modern version (ES6+)
let obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
let arr = Object.values(obj);
let min = Math.min(...arr);
let max = Math.max(...arr);
console.log( `Min value: ${min}, max value: ${max}` );
Original Answer:
Try this:
let obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var arr = Object.keys( obj ).map(function ( key ) { return obj[key]; });
and then:
var min = Math.min.apply( null, arr );
var max = Math.max.apply( null, arr );
Live demo: http://jsfiddle.net/7GCu7/1/
There's no way to find the maximum / minimum in the general case without looping through all the n elements (if you go from, 1 to n-1, how do you know whether the element n isn't larger (or smaller) than the current max/min)?
You mentioned that the values change every couple of seconds. If you know exactly which values change, you can start with your previous max/min values, and only compare with the new ones, but even in this case, if one of the values which were modified was your old max/min, you may need to loop through them again.
Another alternative - again, only if the number of values which change are small - would be to store the values in a structure such as a tree or a heap, and as the new values arrive you'd insert (or update) them appropriately. But whether you can do that is not clear based on your question.
If you want to get the maximum / minimum element of a given list while looping through all elements, then you can use something like the snippet below, but you will not be able to do that without going through all of them
var list = { "a":4, "b":0.5 , "c":0.35, "d":5 };
var keys = Object.keys(list);
var min = list[keys[0]]; // ignoring case of empty list for conciseness
var max = list[keys[0]];
var i;
for (i = 1; i < keys.length; i++) {
var value = list[keys[i]];
if (value < min) min = value;
if (value > max) max = value;
}
You could try:
const obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
const max = Math.max.apply(null, Object.values(obj));
console.log(max) // 5
min and max have to loop through the input array anyway - how else would they find the biggest or smallest element?
So just a quick for..in loop will work just fine.
var min = Infinity, max = -Infinity, x;
for( x in input) {
if( input[x] < min) min = input[x];
if( input[x] > max) max = input[x];
}
// 1. iterate through object values and get them
// 2. sort that array of values ascending or descending and take first,
// which is min or max accordingly
let obj = { 'a': 4, 'b': 0.5, 'c': 0.35, 'd': 5 }
let min = Object.values(obj).sort((prev, next) => prev - next)[0] // 0.35
let max = Object.values(obj).sort((prev, next) => next - prev)[0] // 5
You can also try with Object.values
const points = { Neel: 100, Veer: 89, Shubham: 78, Vikash: 67 };
const vals = Object.values(points);
const max = Math.max(...vals);
const min = Math.min(...vals);
console.log(max);
console.log(min);
// Sorted
let Sorted = Object.entries({ "a":4, "b":0.5 , "c":0.35, "d":5 }).sort((prev, next) => prev[1] - next[1])
>> [ [ 'c', 0.35 ], [ 'b', 0.5 ], [ 'a', 4 ], [ 'd', 5 ] ]
//Min:
Sorted.shift()
>> [ 'c', 0.35 ]
// Max:
Sorted.pop()
>> [ 'd', 5 ]
You can use a reduce() function.
Example:
let obj = { "a": 4, "b": 0.5, "c": 0.35, "d": 5 }
let max = Object.entries(obj).reduce((max, entry) => entry[1] >= max[1] ? entry : max, [0, -Infinity])
let min = Object.entries(obj).reduce((min, entry) => entry[1] <= min[1] ? entry : min, [0, +Infinity])
console.log(max) // ["d", 5]
console.log(min) // ["c", 0.35]
Here's a solution that allows you to return the key as well and only does one loop. It sorts the Object's entries (by val) and then returns the first and last one.
Additionally, it returns the sorted Object which can replace the existing Object so that future sorts will be faster because it will already be semi-sorted = better than O(n). It's important to note that Objects retain their order in ES6.
const maxMinVal = (obj) => {
const sortedEntriesByVal = Object.entries(obj).sort(([, v1], [, v2]) => v1 - v2);
return {
min: sortedEntriesByVal[0],
max: sortedEntriesByVal[sortedEntriesByVal.length - 1],
sortedObjByVal: sortedEntriesByVal.reduce((r, [k, v]) => ({ ...r, [k]: v }), {}),
};
};
const obj = {
a: 4, b: 0.5, c: 0.35, d: 5
};
console.log(maxMinVal(obj));
To get the keys for max and min
var list = { "a":4, "b":0.5 , "c":0.35, "d":5 };
var keys = Object.keys(list);
var min = keys[0]; // ignoring case of empty list for conciseness
var max = keys[0];
var i;
for (i = 1; i < keys.length; i++) {
var value = keys[i];
if (list[value] < list[min]) min = value;
if (list[value] > list[max]) max = value;
}
console.log(min, '-----', max)
For nested structures of different depth, i.e. {node: {leaf: 4}, leaf: 1}, this will work (using lodash or underscore):
function getMaxValue(d){
if(typeof d === "number") {
return d;
} else if(typeof d === "object") {
return _.max(_.map(_.keys(d), function(key) {
return getMaxValue(d[key]);
}));
} else {
return false;
}
}
Using the lodash library you can write shorter
_({ "a":4, "b":0.5 , "c":0.35, "d":5 }).values().max();
var newObj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var maxValue = Math.max(...Object.values(newObj))
var minValue = Math.min(...Object.values(newObj))
obj.prototype.getMaxinObjArr = function (arr,propName) {
var _arr = arr.map(obj => obj[propName]);
return Math.max(..._arr);
}
This works for me:
var object = { a: 4, b: 0.5 , c: 0.35, d: 5 };
// Take all value from the object into list
var valueList = $.map(object,function(v){
return v;
});
var max = valueList.reduce(function(a, b) { return Math.max(a, b); });
var min = valueList.reduce(function(a, b) { return Math.min(a, b); });
If we are sorting date time value then follow the below described procedure
const Obj = {
"TRADE::Trade1": {
"dateTime": "2022-11-27T20:17:05.980Z",
},
"TRADE::Trade2": {
"dateTime": "2022-11-27T20:36:10.659Z",
},
"TRADE::Trade3": {
"dateTime": "2022-11-27T20:28:10.659Z",
}
}
const result = Object.entries(Obj).sort((prev, next) => new Date(prev[1].dateTime) - new Date(next[1].dateTime))
console.log(result)
Related
i have an array of strings with duplicated letters , Now i want to count the number of duplicated letters from each string and need to create a separate object for each string.
The given array :
let ArrOfStrs = ["aaabbbccc", "dddeeefff", "ggghhhiii", "jkl"]
what i have tried :
var obj={}
var repeats=[];
for(let i=0; i< ArrOfStrs.length; i++) {
for(let x = 0; x < ArrOfStrs[i].length; x++) {
var l = ArrOfStrs[i].charAt(x);
obj[l] = (!obj.hasOwnProperty(l) ? 1 : obj[l] + 1);
}
}
repeats.push(obj);
console.log(repeats);
Actual output :
{ a: 3, b: 3, c: 3, d: 3, e: 3, f: 3, g: 3, h: 3, i: 3, j: 1, k: 1, l: 1 }
Expected output :
[{a:3,b:3,c:3}, {d:3,e:3,f:3},{g:3,h:3,i:3},{j:1,k:1,l:1}]
Could some one help for better approach to achieve this.
Thanks in advance.
2 mistakes :
You are keeping a common object obj and making changes to it. Infact obj will be different for every string.
You are not pushing obj into your result array for every iteration. You are doing it in the end, hence you have only one item in your array.
Making minimal changes, your code can be fixed:
let ArrOfStrs = ["aaabbbccc", "dddeeefff", "ggghhhiii", "jkl"]
var repeats=[];
for(let i=0; i< ArrOfStrs.length; i++) {
var obj={}
for(let x = 0; x < ArrOfStrs[i].length; x++) {
var l = ArrOfStrs[i].charAt(x);
obj[l] = (!obj.hasOwnProperty(l) ? 1 : obj[l] + 1);
}
repeats.push(obj);
}
console.log(repeats);
Array.prototype.map to create a new array from an existing one
Array.prototype.reduce to convert an array to a different type (Object)
Spread syntax ... to convert String to Array
const arrOfStrs = ["aaabbbccc", "dddeeefff", "ggghhhiii", "jkl"];
const counted = arrOfStrs.map(str => [...str].reduce((o, v) => {
o[v] ??= 0 // set default count to 0 (if not exists)
o[v]++ // increment count
return o;
}, {}));
console.log(counted);
Additional read:
Nullish coalescent operator ??
Variant:
const arrOfStrs = ["aaabbbccc", "dddeeefff", "ggghhhiii", "jkl"];
const counted = arrOfStrs.map(s => [...s].reduce((o, v) => (o[v] ??= 0, o[v]++, o), {}));
console.log(counted);
I have big array, I want to make an autocomplete search, but I want to display only 10 results, so stop iterating through the array by the time there were found 10 results. I have made this:
let items = array.filter(r => r.indexOf(term)!=-1);
console.log(items.length) // lots of items, need to be limited to 10
It works but I don't know how to stop the array.filter by the time it reaches the desired limit.
You could use another variable to keep track of how many items matched the condition so far and always return false after the limit has been reached. Here is an example:
const arr = [1,0,2,0,3,0,4,5,6,7,8,9,10,11,12,13,14];
const filtered = arr.filter(function(item) {
if (this.count < 10 && item > 0) {
this.count++;
return true;
}
return false;
}, {count: 0});
console.log(filtered);
Here, I'm using an object {count: 0} as the context of the callback function. You can find out more about Array.filter from here
Basically you can use a generator function, which can be stopped by a self made limit, like in the below function
function *filter(array, condition, maxSize) {
if (!maxSize || maxSize > array.length) {
maxSize = array.length;
}
let count = 0;
let i = 0;
while ( count< maxSize && i < array.length ) {
if (condition(array[i])) {
yield array[i];
count++;
}
i++;
}
}
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log( Array.from( filter(array, i => i % 2 === 0, 2 ) ) ); // expect 2 & 4
So it will stop after it reaches maxSize as a parameter, and to easily return it into an array, you can use Array.from, which will iterate the iterator of the generator function
You could hand over a counter and omit any other values for filtering.
const
filter = v => v % 2,
filterMax = (fn, c) => x => c && fn(x) && c--,
max = 3,
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
result = array.filter(filterMax(filter, max));
console.log(result);
Taking the idea of Icepickle's answer a bit ahead with a loop for finding the next valid item and yield this one.
function* filterMax(array, cb, count) {
var i = 0;
while (count) {
while (i < array.length && !cb(array[i])) i++;
if (i >= array.length) return;
yield array[i++];
count--;
}
}
const
filter = v => v % 2,
max = 3,
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(...filterMax(array, filter, max));
You can't break from Array.prototype.filter method. It will loop over every element. You can use a simple for loop and break when 10 items are found
const items = []
for (const value of array) {
if (value.includes(term))
items.push(value)
if (items.length === 10)
break;
}
Just for the trick :
EDIT : To clarify this code will pick the 10 first even number of the list
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
const result = array.reduce((temp, value) => {
if(value%2==0 && temp.length<10)
temp.push(value);
return temp;
}, []);
console.log(result);
var data = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14"]
var limited = data.filter((val,i)=>i<10)
console.log(limited)
You can do this just simple add .Slice(0,NO_OF_ELE_WANT)
eg. finding first two even no
[1,2,3,4,5,6,7,8,9,10].filter((e)=> e%2==0).slice(0,2)
Answer : let items = array.filter(r => r.indexOf(term)!=-1).slice(0,10);
I wrote a library that's handy for this sort of thing.
Here's how I'd find the first 100 numbers that start with the character "1"
const {blinq, range} = window.blinq;
//create a large array of strings to search
const arrToBeSearched = range(0,10000)
.select(x => `${x}`)
.toArray()
const query = blinq(arrToBeSearched)
.where(x => x.startsWith("1"))
.takeWhile((x, i) => i < 100)
const result = [...query] //no calculation until we materialize on this line
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/blinq"></script>
I know its a bit late, but here's for the new comers!
// we'll create a function which will take two arguments
// first argument would be your original array which your want to filter from
// second argument would be the number of results you want the filter to return
const limitedArray = (originalArray, limit) => {
let newArray = [];
for (let item of originalArray) {
if (newArray.length >= limit) break;
//your code here
//in my case i'll jush push in to the array
newArray.push(item)
}
return newArray;
};
//---------------->ignore v<-------------------
//the above function would return an array so in other words we can see this function as an array
const array = [1, 2, 3, 4, 5, 6, 'cascas', 'ascasc', 9, 10, 'ascs'];
console.log(limitedArray(array, 4));
//similarly
limitedArray(array, 4).forEach(item => {
console.log(item)
})
You can define your custom method on Array.prototype which will take 2 arguments. A callback and a max elements that result array will contain.
The code below gets the first 3 odd numbers from array.
function filterUpto(callback,max){
let len = this.length
let res = [];
let i = 0;
while(res.length < max && i < len){
if(callback(this[i],i,this)) res.push(arr[i])
i++
}
return res;
}
Object.defineProperty(Array.prototype,'filterUpto',{
value:filterUpto
})
let arr = [1,2,3,4,5,6,7,8,9,10];
console.log(arr.filterUpto(x => x % 2,3)); //first three odd numbers
Here is another possible solution, pretty straightforward, using Array.from:
const arr = [
"foo",
"bar",
"foobar",
"baz",
"foobaz",
"artefact",
"mortar",
"bar",
"arity",
"mark",
"car",
"dare",
"arbitrary",
"tar",
"jar",
"war",
];
const filterWithLimit = (arr, value, length) =>
Array.from(
{ length },
function () {
return arr
.slice(this.index++)
.find((option, i) => (this.index += i, option.includes(value)));
},
{ index: 0 }
);
console.log(filterWithLimit(arr, "ar", 10));
Here is a short solution which doesn't continue searching after the limit is reached:
function filter_n(array, limit, test) {
let ret = []
array.find((x)=> test(x) && ret.push(x)>=limit )
return ret
}
when test(x) is true, it calls ret.push(x) (which adds x to ret and outputs the length of ret)
then, once ret's length is >= limit, the inner function returns true, and find stops looping because it "found" a result
I want to perform the sum operation on each subarray using javascript using forEach,map,reduce function, so that ultimately my output should look like:
sum = [8,13,22]
but I am not getting the desired output. Please assist where I am going wrong.Thanks.
var Data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
var newArr = [];
Data.forEach(function(item) {
item = item.reduce(function(a, b) {
return a + b;
});
newArr.push([item]);
});
console.log(newArr);
You could map the summed values, literately.
var data = [{ a: 1, b: 2, c: 5 }, { a: 3, b: 4, c: 6 }, { a: 6, b: 7, c: 9 }],
result = data.map(o => Object.values(o).reduce((a, b) => a + b));
console.log(result);
Just some annotation to the given code:
You can not iterate an object with reduce, because that works only for array. To overcome this problem, you need just the values of the object by taking Object.values and then, you could iterate the values.
Then return the sum without wrapping it in an array.
var Data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
var newArr = [];
Data.forEach(function(item) {
var sum = Object.values(item).reduce(function(a, b) {
return a + b;
});
newArr.push(sum);
});
console.log(newArr);
A better solution would be the use of Array#map, because you need one value for each element of the array.
var data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
newArr = data.map(function(item) {
return Object.values(item).reduce(function(a, b) {
return a + b;
});
});
console.log(newArr);
As per your example, Old way
var Data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
var newArr = [];
Data.forEach(function(object) {
let sum = 0;
for (var property in object) {
if (object.hasOwnProperty(property)) {
sum += object[property]
}
}
newArr.push(sum);
});
console.log(newArr);
I have an array with two values, (1 or 2) and (a, b, c or d). Depending on the two values a certain math function will execute. The function takes an separate inputted number and multiplies it by a constant, but that part isn't necessary to this.
Essentially a user provides the 3 values, I've already removed the one value which is the constant 'k', so I'm left with 2 values that determine the right multiplier for the constant 'k'.
I'm looking for something that would be easier and more robust than combining the array and running through all the possible solutions in a switch statement. There is a possibility of new variables for the array in the future.
let k = 5;
let input = [2, 'c'];
if (input.join().includes('1')) {
if (input.join().includes('a')) {
return k * 10;
};
else if (input.join().includes('b')) {
return k * 11;
};
else if (input.join().includes('c')) {
return k * 12;
};
else if (input.join().includes('d')) {
return k * 13;
};
};
else if (input.join().includes('2')) {
if (input.join().includes('a')) {
return k * 14;
};
else if (input.join().includes('b')) {
return k * 15;
};
else if (input.join().includes('c')) {
return k * 16;
};
else if (input.join().includes('d')) {
return k * 17;
};
};
Basically I have something like this right now. input and k are provided by the user, but not necessarily in any certain order, so I can't reliable assume input[1] will give me (a, b, c or d).
I agree with Patrick's comment that there is a bit of mystery around what you're actually trying to do here. I also noticed your comment:
would I be able to add: var mathFuncs = { 1: 'one': { a: mathFunc10, b: mathFunc20 }
Are you saying you would like to be able to accept input values of 1 or one interchangeably?
You can do this very simply. The calculate() function below makes a copy of the input array with each element converted to a number if it is one of the number names, then sorts this array to put it in a consistent order (numbers sort before letters). Next, we select which list of multipliers to use (1 or 2), and finally get the specific multiplier (a-d) to calculate the return value. If the input array doesn't match anything, we return NaN.
const numbers = {
'one': 1,
'two': 2,
};
const multipliers = {
1: { a:10, b:11, c:12, d:13 },
2: { a:14, b:15, c:16, d:17 },
};
function calculate( k, input ) {
const convert = n => numbers[ n.toString().toLowerCase() ] || n;
const sorted = input.map( convert ).sort();
const list = multipliers[ sorted[0] ];
if( ! list ) return NaN;
const multiplier = list[ sorted[1] ];
return multiplier == null ? NaN : k * multiplier;
}
function test( k, input) {
console.log( k, input.toString(), calculate( k, input ) );
}
test( 5, [ 1, 'a' ] ); // 50
test( 5, [ 'a', 1 ] ); // 50
test( 5, [ 'a', 'one' ] ); // 50
test( 5, [ 2, 'c' ] ); // 80
test( 5, [ 'two', 'c' ] ); // 80
test( 5, [ 2, 'e' ] ); // NaN
test( 5, [ 3, 'a' ] ); // NaN
test( 5, [ 'three', 'a' ] ); // NaN
var mathFunc = getMathFunc([2, 'b']);
mathFunc(2); // 80
function getMathFunc(arr) {
var inputString = arr.join('');
var mathFuncs = {
1: {
a: mathFunc10,
b: mathFunc20
},
2: {
a: mathFunc30,
b: mathFunc40
}
};
for (var numKey in mathFuncs) {
if (inputString.includes(numKey)) {
var numObj = mathFuncs[numKey];
for (var letterKey in numObj) {
if (inputString.includes(letterKey)) {
return numObj[letterKey];
}
}
}
}
function mathFunc10(num) {
return 10 * num;
}
function mathFunc20(num) {
return 20 * num;
}
function mathFunc30(num) {
return 30 * num;
}
function mathFunc40(num) {
return 40 * num;
}
}
If the logic of the returned value is like in your example, then this will do it:
const ref = { 1: 10, 2: 14, a: 0, b: 1, c: 2, d: 3 },
calc = (k, input) => k * input.reduce( (res, x) => res + ref[x], 0 );
// Sample calls:
console.log([
calc(5, [2, 'c']), // 80
calc(5, ['c', 2]), // 80
calc(5, ['a', 1]), // 50
calc(5, [2, 'b']), // 75
calc(5, [3, 'd']), // NaN
calc(5, ['e', 2]), // NaN
]);
Of course, if the logic is more complex in other cases, then you'll have to implement that logic in your function and/or the proposed ref mapping object. If the "variables" are more interdependent, you may even need several mapping objects.
I have this javascript:
function padded_array(k, value){
var a = [];
a[k] = value;
return a;
}
padded_array(3, "hello"); //=> [undefined, undefined, undefined, 'hello']
Is it possible to shorten the code in the function body?
for all the googlers coming here - you're probably looking for this:
var pad_array = function(arr,len,fill) {
return arr.concat(Array(len).fill(fill)).slice(0,len);
}
From 2020 & 2021 : straight forward options
Let assume that is your Array
const yourArray = [1,2]
If you just want to loop 4 times (maybe for react jsx )
Array.from({length:4}) //[undefined,undefined,undefined,undefined]
Array(4).fill()//[undefined,undefined,undefined,undefined]
If you want to loop yourArray 4 times, but to start with values you already have
// unmutation option
Array.from({...yourArray, length:4}) //[1,2,undefined,undefined]
// unmutation option, but need some calcualtion
[...yourArray , ...Array(2) ] //[1,2,undefined,undefined]
[...Array(2), ...yourArray ] //[undefined,undefined,1,2]
// loop on your array several times
Array(3).fill(yourArray).flat() // [1, 2, 1, 2, 1, 2]
// mutation the original array.
yourArray.length = 4;
Array.from(yourArray) //[1,2,undefined,undefined]
If You actually want an Array with full of values. ex. with increment numbers.
Remap it
// unmutation option
Array.from({...yourArray,length:4}, (v,i) => v ?? i+1 )
// [1,'2',3, 4]
// Or, mutation the original array. and fill with "x"
array.yourArray.length = 4;
Array.from(yourArray, (v) => v ?? 'x')
// [1,'2','x','x']
If you want to exclude the 'hello', you can use
new Array(count);
to create padded Arrays.
Edit: Maybe like this ?
new Array(5).concat("hello")
Another solution using spread operator:
padArray = (length, value) => [...Array(length).fill(), value];
And the usage is the same as you mentioned:
padded_array(3, "hello"); //=> [undefined, undefined, undefined, 'hello']
For padding at the start:
function padArrayStart(arr, len, padding){
return Array(len - arr.length).fill(padding).concat(arr);
}
Demo:
function padArrayStart(arr, len, padding){
return Array(len - arr.length).fill(padding).concat(arr);
}
console.log(...padArrayStart([1,2,3], 5, 0));//0 0 1 2 3
console.log(...padArrayStart([4,5,6], 3, 0));//4 5 6
For padding at the end:
function padArrayEnd(arr, len, padding){
return arr.concat(Array(len - arr.length).fill(padding));
}
Demo:
function padArrayEnd(arr, len, padding){
return arr.concat(Array(len - arr.length).fill(padding));
}
console.log(...padArrayEnd(['a','b','c'], 10, 'z'));//a b c z z z z z z z
console.log(...padArrayEnd([0, 'a', 'd'], 6, -1));//0 a d -1 -1 -1
Not in standard ES5 or predecessor. Surely you can do something like $.extend([], {"3": "hello"}) in jQuery; you can even do
Object.create(Array.prototype, {"3": {value: "hello"} });
in bare ES5, but it is hack, I would not consider this a solution (if it is ok with you, you can adopt it).
You can use that if your JS doesn't support Array.prototype.fill() (ex. Google Apps Script) and you can't use the code from the first answer:
function array_pad(array, length, filler)
{
if(array.length < length)// [10.02.20] Fixed error that Dimitry K noticed
while(true)
if(array.push(filler) >= length)
break;
return array;
}
I know this is an old(er) question but wanted to add my 2 cents if someone stumbles here (like i initially did).
Anyway, heres my take with Array.from
const padded_array = (k, value) => Array.from({ length: k }).concat(value)
console.log(padded_array(3, "hello"));
Also you could do it with something like this:
const padded = (arr, pad, val) => {
arr[pad] = val
return arr
}
console.log(padded([],3,'hello'))
// push is faster than concat
// mutate array in place + return array
const pad_right = (a, l, f) =>
!Array.from({length: l - a.length})
.map(_ => a.push(f)) || a;
const a = [1, 2];
pad_right(a, 4, 'x');
// -> [ 1, 2, 'x', 'x' ]
a;
// -> [ 1, 2, 'x', 'x' ]
function leftPad(array, desiredLength, padding) {
array.unshift(...Array(desiredLength - array.length).fill(padding));
}
function rightPad(array, desiredLength, padding) {
array.push(...Array(desiredLength - array.length).fill(padding));
}
const myHello = ['hello'];
leftPad(myHello, 3, undefined);
// [undefined, undefined, 'hello']
const myHello2 = ['hello2'];
rightPad(myHello, 3, 0);
// ['hello2', 0, 0];