create array of object from array of strings - javascript

I am trying to solve one issue in my code, so if anyone can help me here?
I have some values added below, So i have one array of string values, which has mac addresses and min & max which is constant values. I am trying to map over macValue and trying to create array of object as given sample below, but unfortunately getting some error there. If anyone can help me out here.
please check here i am trying to dynamically add property inside map.
let macValue = ["MO-CK-DR-01","02","03"]
let min = true
let max = true
// code i have tried
var print = macValue.map((item, i) => {
(item['macAddress'] = item), (item.minimum = min), (item.maximum = max);
return item;
});
trying to create array of object like this
[
{
macAddress: value, //01
mimimum: min,
maximum: max,
},
{
macvalue: value, // 02
mimimum: min,
maximum: max,
},
]
but didn't work and getting this error

As simple as:
let macValue = ["MO-CK-DR-01","02","03"]
let min = true
let max = true
const obj = macValue.map((value) => ({
macvalue: value,
minimum: min,
maximum: max,
}))

let macValue = ['MO-CK-DR-01', '02', '03'];
let min = true;
let max = true;
const result = macValue.map((value) => ({
macValue: value,
minimum: min,
maximum: max
}));
console.log(result);

let macValue = ['MO-CK-DR-01', '02', '03'];
let min = true;
let max = true;
const output = macValue.map(value => ({
macValue: value,
minimum: min,
maximum: max
}));
console.log(output);

As you mentioned, the properties are dynamic, I have used string properties. This should work -
let macValue = ['MO-CK-DR-01', '02', '03'];
let min = true;
let max = true;
const result = macValue.map((value) => ({
'macAddress': value,
'minimum': min,
'maximum': max
}));
console.log(result);

Related

Why is this attempt to retrieve the minimum number of an array not working?

Max should be = 9.99, and min should be = 6.88
let arr = [["2019","00","01", 9.99], ["2018","00","01", 9.32], ["2017","00","01", 6.88]]
let max = Math.max(Number(...arr.map((o) => { return o[3] }))); //9.99
let min = Math.min(Number(...arr.map((o) => { return o[3] }))); //9.99
console.log(min);
console.log(max);
let arr = [["2019","00","01", 9.99], ["2018","00","01", 9.32], ["2017","00","01", 6.88]];
let max = Math.max(...arr.map((o) => { return o[3] })); //9.99
let min = Math.min(...arr.map((o) => { return o[3] })); //6.88
console.log({
max , min
})
Earlier, you had put Number around the mapped array. This converts the array to a number. However, you only wanted the individual elements to be numbers so move it inside the map function.
let arr = [
["2019","00","01", 9.99],
["2018","00","01", 9.32],
["2017","00","01", 6.88]
];
let max = Math.max(...arr.map((o) => { return Number(o[3]) })); //9.99
let min = Math.min(...arr.map((o) => { return Number(o[3]) })); //6.88
// this can be rewritten like so:
// Math.min(...arr.map((o) => Number(o[3])));
//
// https://www.w3schools.com/js/js_arrow_function.asp
console.log(max);
console.log(min);
So,
before:
let min = Math.min(Number(...arr.map((o) => { return o[3] }))); //9.99
after
let min = Math.min(...arr.map((o) => { return Number(o[3]) })); //6.88

How to populate an array with integers

Please, how do you populate an array say ‘num’ with numbers not in a second array say ‘fig’? I’m trying to use a loop to have the values of the already populated array ‘fig’ compared to ‘num’ which is to be populated with integers not found in ‘fig’. I’m a bit confused.
If you need to do an array with n numbers you can use this two ways.
const arrayLength = 100;
const numberArray = [...new Array(arrayLength).keys()]
const anotherWay = new Array(arrayLength).fill().map((_, idx) => idx + 1);
console.log(numberArray, anotherWay)
so to do this we have to do a few things:
1) define an existing array with numbers to avoid
2) define length on new array
3) generate a random number and make it an integer
4) check to see if we need to avoid
5) if it's a new value add it to the second array
var first=[55,45,35,1,2,3,4,5];
var second = [];
var i = 7;
var x;
while (i != 0){
x = ~~(Math.random()*100);
var check = false;
for(let j=0; j<first.length;j++){
if(x == first[j]){
check = true;
}
}
if(!check){
second.push(x);
i--;
}
}
console.log(second);
const fig = [-21, 0, 3, 6, 7, 42]
const min = Math.min(...fig) // or fig[0] if the the array is already sorted
const max = Math.max(...fig) // or fig[fig.length - 1]
const num = Array.from({ length: max - min }, (_, i) => i + min)
.filter(el => !fig.includes(el))
or, saving one loop
const num = Array.from({ length: max - min }).reduce((acc, _, i) => {
const curr = i + min
if (!fig.includes(curr)) {
return acc.concat(curr)
}
return acc
}, [])
This is assuming your range is from the smallest number in fig to the largest in fig.

Javascript: Convert string to array of objects?

Tell me, how can I optimally convert a string like
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
to an array like
const range = [
{
min: 1350,
max: 1350,
},
{
min: 1351,
max: 1351,
},
{
min: 1390,
max: 1391,
},
{
min: 1401,
max: 1401,
},
{
min: 1402,
max: 1407,
},
];
?
In other words, you need to create an array of number ranges using a string in which these numbers ranges are explicitly specified.
The most obvious of the possible algorithms is:
1) split the string using a delimiter,
2) the resulting parts are cleaned of spaces using the command trim
3) check whether the part is a number
4) if not, then split the part using the delimiter -
5) the parts obtained are cleaned of spaces using the command trim,
6) check that the amount of component eq 2 and it's a number
But is it possible to make it more optimal, more beautiful, more effective?
You can use .split() and .map():
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
const range = data.split(",").map(s => {
let [min, max = min] = s.split("-");
return {min: Number(min), max: Number(max)}
});
console.log(range);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try something like this:
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407"
const result = data
.split(/\s*,\s*/)
.map(pair => {
const [min, max = min] = pair
.split(/\s*-\s*/)
.map(Number)
return {
min,
max
}
})
console.log(result)
You can use split method in combination with reduce method.
The reduce() method applies a function against an accumulator and each
element in the array (from left to right) to reduce it to a single
value.
Also, use + operator in order to force result to Number.
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
const array = data.split(', ').reduce(function(arr, elem){
var [min, max] = elem.split('-');
arr.push({
min : + min,
max: + (max || min)
});
return arr;
},[]);
console.log(array);
I think the simple and much understandable way would be to loop through the values and check if they have a range value (with hyphen) and create the object accordingly for the range array.
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
var range = [];
data.split(',').forEach((val)=>{
var obj = {};
if(val.indexOf('-') === -1 ){
obj.min = val;
obj.max = val;
} else {
obj.min = val.split('-')[0].trim();
obj.max = val.split('-')[1].trim();
}
range.push(obj);
});
console.log(range);
This code will help you.
const data = "1350, 1351, 1390-1391, 1401, 1402 - 1407";
var arr = data.split(',');
const range = [];
for(var i=0; i< arr.length; i++){
var b = arr[i].split('-');
if(!b[1])b[1]=b[0];
var obj = new Object();
obj.min = parseInt(b[0]);
obj.max = parseInt(b[1]);
range.push(obj);
}
console.log(range);

how to filter a set of data by variance in typescript?

Let's say I have a set of data like this with a row for each minute in the last 4 hours:
[
{ X:1000, Y:2000, Z:3000, DateTime: 12/15/2018 12:00 },
{ X:998, Y:2011, Z:3020, DateTime: 12/15/2018 12:01 }
]
I need an array of property names whose values are within a 20% variance for all rows. So if Y and Z above meet this criteria but X does not then the output should look like this:
[Y, Z]
What typescript code could I use to do this?
I don't know exactly what "variance" or "variance percentage" mean in your question. I just used this formula to calculate variance: https://www.wikihow.com/Calculate-Variance
For the variance percentage, I simply divided the variance by the mean value and expressed it in percentage.
Feel free to replace my calculateVariancePercentage with a more correct implementation.
const ACCEPTABLE_VARIANCE_THRESHOLD = 20;
const dataset = [
{ X:1000, Y:2000, Z:3000, DateTime: '12/15/2018 12:00' },
{ X:998, Y:2011, Z:3020, DateTime: '12/15/2018 12:01' }
];
const calculateVariancePercentage = (data) => {
const meanValue = data.reduce((sum, element) => sum + element, 0) / data.length;
const sumOfDeviations = data.reduce((sod, element) => Math.pow(element - meanValue, 2), 0);
const variance = sumOfDeviations / (data.length - 1);
return variance / meanValue * 100;
}
const variables = Object.keys(dataset[0]).filter(key => key !== 'DateTime');
const result = variables.filter(variable => {
const varData = dataset.map(row => row[variable]);
const varianceInPercentage = calculateVariancePercentage(varData);
console.log(varianceInPercentage);
return calculateVariancePercentage(varData) <= ACCEPTABLE_VARIANCE_THRESHOLD;
});
console.log(result);

find min and max value using reduce es2015

If I have array of object like this
[{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}]
How to find min and max using reduce? I know I can use generic loop and compare but I would like to explore reduce in es2015
You can use reduce like this to get the min and max numbers from each object in the array.
const arr = [{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}]
console.log(
arr.reduce((acc, x) => {
acc.min = Math.min(acc.min, x.min)
acc.max = Math.max(acc.max, x.max)
return acc
}, { min: Infinity, max: -Infinity })
)
// as Bergi suggested, we could just return a new Object literal
// from the reduction
console.log(
arr.reduce((acc, x) => ({
min: Math.min(acc.min, x.min),
max: Math.max(acc.max, x.max)
}), { min: Infinity, max: -Infinity })
)
Assuming that you want, for the minimum, to get the id of the item with the lowed min value, then this will do it.
const items = [{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}];
// Reduce to find the item with the lowest min
const min = items.reduce((res, item) => {
// No result yet, so the item must be the lowest seen
if (!res) return item;
// Use the lowest of the current lowest and the current item
return item.min < res.min ? item : res;
}, undefined).id;
const arr = [{min:5,max:10,id:1}, {min:50,max:3,id:2}, {min:1,max:40,id:3}];
const min = arr.reduce((m, o) => m < o.min? m: o.min, +Infinity),
max = arr.reduce((M, o) => M > o.max? M: o.max, -Infinity);
console.log("Min:", min);
console.log("Max:", max);
Explanation of min:
const min = arr.reduce((m, o) => { // for each object o in the array arr
return m < o.min? // if o.min is bigger than the minimum m
m: // then the minimum is still m
o.min; // otherwise, the new minimum is o.min
}, +Infinity); // pass in +Ifinity as the minimum (the initial value of m so whatever is arr[0].min is it will be smaller than m). You can pass in arr[0].min if you want instead of +Infinity

Categories