info before: i have halfway succeded, as i managed to print out it and it didnt loop crazy, however i did not manage to find the reason why it still prints out a undefinded
HTML: <button id="btn">button</button>
<label id="textarea"></label>
var tall = [4, 5, 2, 3, 4, 6, 1, 2, 0, 9, 7, 6, 8, 5, 6, 4, 2, 3, 5]
var btn = document.getElementById("btn");
tall.sort(function(a, b){return a-b})
btn.onclick = function(){
for( var i = 0; i < tall.length; i ){
a = 0;
for(var j = 0; j<i ; j ){
a ;
tall.splice(i, 2)
document.write("number " tall[i] " is " a " times<br>")
}
}
}
CodePudding user response:
- we can use reduce to calculate how many times number is shown
- then we can use
Object.entries
withforEach
- to show data to UI
var tall = [4, 5, 2, 3, 4, 6, 1, 2, 0, 9, 7, 6, 8, 5, 6, 4, 2, 3, 5]
var btn = document.getElementById("btn");
btn.onclick = function(){
const objectResult = tall.reduce((a,c) => (a.hasOwnProperty(c) ? {...a, [c]: a[c] 1} : {...a, [c]: 1}), {});
Object.entries(objectResult).forEach(([number, times]) => document.write(`number: ${number} is ${times} times<br>`))
}
<button id="btn">button</button>
<label id="textarea"></label>
CodePudding user response:
Using the reduce function, you can iterate over your array and generate an output based on action you perform on each next Value in the Array. We start with an empty object, if we find that the nextValue is not yet stored we store it in that object with value 1, if we see that the nextValue already exists, we increment the count in the result.
const data = [4, 5, 2, 3, 4, 6, 1, 2, 0, 9, 7, 6, 8, 5, 6, 4, 2, 3, 5]
const result = data.reduce((result, nextValue) => {
if (nextValue in result)
result[nextValue]
else
result[nextValue] = 1
return result
}, {}) // initial result is an empty object set with ', {}'
console.log(result)
CodePudding user response:
var tall = [4, 5, 2, 3, 4, 6, 1, 2, 0, 9, 7, 6, 8, 5, 6, 4, 2, 3, 5];
var map = tall.reduce(function(prev, cur) {
prev[cur] = (prev[cur] || 0) 1;
return prev;
}, {});
console.log(map)
CodePudding user response:
Here you go:
const list = document.querySelector('ul')
const button = document.querySelector('button')
const tall = [4, 5, 2, 3, 4, 6, 1, 2, 0, 9, 7, 6, 8, 5, 6, 4, 2, 3, 5]
// Cals result
const result = tall.reduce((res, value) => {
if (value in res)
res[value]
else
res[value] = 1
return res
}, {})
button.addEventListener('click', () => {
list.innerHTML = ''
// Add li element for each result
Object.keys(result).forEach(res => {
const li = document.createElement('li')
li.textContent = `${res} occures ${result[res]} times`
list.append(li)
})
})
<button>Write data to list</button>
<ul>
<ul>
- This will give you the occurrences of each number in an object.