Make all numbers in array Absolute value in Javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to make all values in the below array absolute, after trying several methods the results that appears is 5 the first element in the array. the below is the code given:
describe('absoluteValueArray', () => {
it('Gets multiple absolute values', () => {
const result = absoluteValueArray([-5,-50,-25,-568])
expect(result).toEqual([5,50,25,568])
})
})
Function I tried is the below:
const absoluteValueArray = (array) => {
var index, len;
var array = ["-5", "-50", "-25" , "-568"];
for (index = 0, len = array.length; index < len; ++index) {
let res = Math.abs(array[index]);
return res;
}
}

You approach does not work in this line and the next
let res = Math.abs(array[index]);
return res;
because you need to assign the absolute value to the array or a new array at the same index, like
resultArray[i] = Math.abs(array[index]);
and return the array after finishing the loop.
The original return inside of the loop exits the loop with the first element.
Instead, you could take Math.abs as callback for Array#map.
const absoluteValueArray = (array) => {
return array.map(Math.abs);
}
console.log(absoluteValueArray([-5, -50, -25, -568]));

Related

How to check the array is of how many dimension in javascript? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
For example I have an array as follows & expected output is given.
In javascript how can we determine dynamically how many levels are there in my array ary.
var ary = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]];
Output: 3
var ary = ["a","b",["c","d"],"e",["f","g","i"]];
Output: 2
var ary = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
Output: 4
Here is a reccursive function that will traverse through the depths of the array and track the maximum of it. Note that the tracking is done via properties attach to the function itself.
var ary1 = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
function getDimension(arr, start) {
//Attach depth tracking properties to the function
if (start){
getDimension.depth = 0;
getDimension.maxDepth = 0;
}
//Track max depth
getDimension.depth++
if (getDimension.depth > getDimension.maxDepth)
getDimension.maxDepth++;
//Manage recursion
for (let element of arr)
if (element instanceof Array)
getDimension(element);
getDimension.depth--;
//In first level at this point
if (getDimension.depth === 0)
return getDimension.maxDepth;
}
let d = getDimension(ary1, true);
console.log(d);

Does a map update automatically if the original array is updated? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am creating an array in a for loop and using a map to keep track of the number of times I've used certain values (e.g. key: count; "AB": 2, "BC": 3). I've declared the empty array and created the map for that, outside the loop.
Inside the loop, I'm updating the array based on the value in the map ( if (map.get(x) < 3) {array[i] = x}).
I'm assuming the condition isn't working because I'm not updating the map, but is there a way to have the map update automatically as the array is updated?
var array = [];
var map = array.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
for (var i = 0; i < 24; i++) {
var random = Math.floor(Math.random() * 10)
if (map.get(random) < 3) {
array[i] = random
}
}

JavaScript Infinity loop in foreach statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i wrote this code and he executed in an infinite loop
var listStock=[{"price":200,"libelle":"bus"},{"price":5,"libelle":"grand taxi"},{"price":6,"libelle":"tram"},{"price":12,"libelle":"tram"},{"price":95,"libelle":"librairie"},{"price":22,"libelle":"food"},{"price":6,"libelle":"tram"},{"price":6,"libelle":"tram"},{"price":15,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":10.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":13.5,"libelle":"librairie"},{"price":20,"libelle":"librairie"},{"price":20,"libelle":"arrondissement"},{"price":15,"libelle":"grand taxi"},{"price":9,"libelle":"librairie"},{"price":34,"libelle":"food"},{"price":10,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":3.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":7.5,"libelle":"grand taxi"},{"price":33,"libelle":"tran"},{"price":4,"libelle":"pisri"},{"price":15,"libelle":"grand taxi"},{"price":5,"libelle":"pisri"},{"price":20,"libelle":"tobis"},{"price":6,"libelle":"grand taxi"},{"price":45,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":4,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":120,"libelle":"tran"},{"price":3,"libelle":"librairie"},{"price":8,"libelle":"pisri"},{"price":60,"libelle":"covoiturage"},{"price":7,"libelle":"grand taxi"},{"price":7,"libelle":"tram"},{"price":2,"libelle":"pisri"},{"price":1,"libelle":"gift"},{"price":29,"libelle":"food"},{"price":23,"libelle":"covoiturage"}];
var listLib=[];
listStock.forEach(function(item, index) {
var lib=item.libelle;var pr=item.price;
if(listLib.length==0){
var objet={};objet.libelle=lib;objet.price=pr;
listLib.push(objet);
}else{
listLib.forEach(function(item1,index1){
if(item1.libelle==lib){
item1.price=item1.price+pr;
}else{
var objet={};objet.libelle=lib;objet.price=pr;
listLib.push(objet);
}
});
}
});
i want to sum prices by label
You are using listLib.push inside a loop on listLib, and you are doing this for every iteration where the object does not match. And so you repeatedly add a similar object to listLib.
You should just find the matching entry, and potentially add a new object after that search, not during the search. So if we stick to your code, then the else part of your code should be modified to this:
var found = false;
for (let item1 of listLib) {
if(item1.libelle==lib){
item1.price=item1.price+pr;
found = true;
break; // No need to look further
}
}
// And then AFTER the loop, check if we need to add the object:
if (!found) {
var objet={};objet.libelle=lib;objet.price=pr;
listLib.push(objet);
}
Even better is to key your input data first, using a Map. Because then the look-up is easy and has better performance:
var listStock=[{"price":200,"libelle":"bus"},{"price":5,"libelle":"grand taxi"},{"price":6,"libelle":"tram"},{"price":12,"libelle":"tram"},{"price":95,"libelle":"librairie"},{"price":22,"libelle":"food"},{"price":6,"libelle":"tram"},{"price":6,"libelle":"tram"},{"price":15,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":10.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":13.5,"libelle":"librairie"},{"price":20,"libelle":"librairie"},{"price":20,"libelle":"arrondissement"},{"price":15,"libelle":"grand taxi"},{"price":9,"libelle":"librairie"},{"price":34,"libelle":"food"},{"price":10,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":3.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":7.5,"libelle":"grand taxi"},{"price":33,"libelle":"tran"},{"price":4,"libelle":"pisri"},{"price":15,"libelle":"grand taxi"},{"price":5,"libelle":"pisri"},{"price":20,"libelle":"tobis"},{"price":6,"libelle":"grand taxi"},{"price":45,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":4,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":120,"libelle":"tran"},{"price":3,"libelle":"librairie"},{"price":8,"libelle":"pisri"},{"price":60,"libelle":"covoiturage"},{"price":7,"libelle":"grand taxi"},{"price":7,"libelle":"tram"},{"price":2,"libelle":"pisri"},{"price":1,"libelle":"gift"},{"price":29,"libelle":"food"},{"price":23,"libelle":"covoiturage"}];
let map = new Map(listStock.map(({libelle}) => [libelle, {libelle, price: 0}]));
for (let {price, libelle} of listStock) map.get(libelle).price += price;
let result = Array.from(map.values());
console.log(result);
var listStock=JSON.parse(`[{"price":200,"libelle":"bus"},{"price":5,"libelle":"grand taxi"},{"price":6,"libelle":"tram"},{"price":12,"libelle":"tram"},{"price":95,"libelle":"librairie"},{"price":22,"libelle":"food"},{"price":6,"libelle":"tram"},{"price":6,"libelle":"tram"},{"price":15,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":10.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":13.5,"libelle":"librairie"},{"price":20,"libelle":"librairie"},{"price":20,"libelle":"arrondissement"},{"price":15,"libelle":"grand taxi"},{"price":9,"libelle":"librairie"},{"price":34,"libelle":"food"},{"price":10,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":3.5,"libelle":"food"},{"price":23,"libelle":"grand taxi"},{"price":12,"libelle":"tram"},{"price":7.5,"libelle":"grand taxi"},{"price":33,"libelle":"tran"},{"price":4,"libelle":"pisri"},{"price":15,"libelle":"grand taxi"},{"price":5,"libelle":"pisri"},{"price":20,"libelle":"tobis"},{"price":6,"libelle":"grand taxi"},{"price":45,"libelle":"grand taxi"},{"price":7.5,"libelle":"grand taxi"},{"price":4,"libelle":"librairie"},{"price":7.5,"libelle":"grand taxi"},{"price":120,"libelle":"tran"},{"price":3,"libelle":"librairie"},{"price":8,"libelle":"pisri"},{"price":60,"libelle":"covoiturage"},{"price":7,"libelle":"grand taxi"},{"price":7,"libelle":"tram"},{"price":2,"libelle":"pisri"},{"price":1,"libelle":"gift"},{"price":29,"libelle":"food"},{"price":23,"libelle":"covoiturage"}]`);
//console.log(listStock)
const finalData=listStock.reduce((acc,curr)=>{
const label=curr.libelle;
acc[label]=acc[label]? acc[label]+ curr.price : curr.price || 0;
return acc;
},{})
console.log(finalData)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Data in Array is Incomplete [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Data in Array is Incomplete
it get only last item.
I need to get all item.
how to fix this?
source code
let GetProvinceWithSumCovid19 = [];
for (let index = 0; index < GetProvince.length; index++) {
GetProvinceWithSumCovid19 = dataFromAmCharts.filter(x => x.name.indexOf(GetProvince[index].providersEN) > -1);
GetProvinceWithSumCovid19.push({
value: GetProvince[index].sumCovid19
})
};
console.log(GetProvinceWithSumCovid19);
The first line in the for loop overwrites GetProvinceWithSumCovid19
There's not a lot of information to go off of here, but looking at the second image of the output, I believe you're trying to do something like this:
const getProvinceWithSumCovid19 = GetProvince.map((item, index) => {
return {
[dataFromAmCharts.filter(x => x.name.indexOf(GetProvince[index].providersEN) > -1)],
value: GetProvince[index].sumCovid19
}
});
console.log(getProvinceWithSumCovid19);
Instead of assigning to GetProvinceWithSumCovid19 variable, push to it.
var GetProvinceWithSumCovid19 = [];
for (let index = 0; index < GetProvince.length; index++) {
GetProvinceWithSumCovid19.push(dataFromAmCharts.filter(x => x.name.indexOf(GetProvince[index].providersEN) > -1));
GetProvinceWithSumCovid19.push({
value: GetProvince[index].sumCovid19
})
};
console.log(GetProvinceWithSumCovid19);
The output structure would be like:
[[{id:, name:},{id:, name:}], {value:2}, [{id:, name:}], {value:1}]
But I really doubt whether this is the structure you want. The required output structure is not clear in your question.

JS loop producing no result [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Trying to create an array with a loop and then sum all the contents of the array and put the result as the contents of a DIV but when I run the fiddle I get no result and jshint says everything is well formed.
var begin = 500000;
var stop = 999999;
var arrInt = [];
// Create an array worth summing
var CreateArray = function (begin,stop) {
while(begin < stop +1){
arrInt.push(begin++);
}
};
// Sum all ints in an array
var IntSum = function (ManyInts) {
var i = arr.length; while (i--) {
return;
}
};
var example = document.getElementById("example").innerHTML;
example=IntSum(arrInt);
<div id="example"></div>
http://jsfiddle.net/7b8rqme5/
At no point do you call CreateArray. You call your other function, IntSum, which does precisely nothing. Also, you create a variable example and assign a dom element to it, then you immediately overwrite it with a (noop) function result. There are additional issues with your code as well.
My advice: slow down, determine what it is you need to accomplish, and take it step by step.
I think this is what you wanted. But not really sure what you are trying to do here.
var begin = 500000;
var stop = 999999;
var arrInt = [];
var CreateArray = function (begin,stop) {
while(begin < stop +1){
arrInt.push(begin++);
}
};
var IntSum = function (ManyInts) {
var sum = 0
var i = ManyInts.length; while (i--) {
sum += ManyInts[i];
}
return sum;
};
var example = document.getElementById("example").innerHTML;
CreateArray(begin, stop);
var saic=IntSum(arrInt);
document.getElementById("example").innerHTML = saic
http://jsfiddle.net/wpnkL6k2/

Categories