Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What is the best way to loop through a json object that contains integer values and select the smallest values?
For example, if I had an object that looks like this
var z =
{"a": 4,
"b":2,
"c":5,
"d":1,
"e":3
}
And I wanted to pick out the 3 smallest numbers - 1,2,3 in this case- what's the best approach?
You could try the following script:
// create an array to store the values.
var numbers = [];
// loop through the keys of z and push each value in the numbers array.
for(var key in z){
numbers.push(z[key]);
}
// sort the array.
numbers = numbers.sort(function(a,b){ return a-b; });
// pick up the first three.
firstThree = numbers.slice(0,3);
var z =
{"a": 4,
"b":2,
"c":5,
"d":1,
"e":3
}
var numbers = [];
for(var key in z){
numbers.push(z[key]);
}
numbers = numbers.sort(function(a,b){ return a-b; });
firstThree = numbers.slice(0,3);
alert(firstThree)
Get object values into an array using for...in loop. Then sort it using sort() and get the values
Update : You can get the first 3 values using splice()
var z = {
"a": 4,
"b": 2,
"c": 5,
"d": 1,
"e": 3
},
arr = [];
// array for storing values
for (var o in z)
// iterate over the array
arr.push(z[o]);
// push value to the array
document.write(arr
.sort()
// sorting the value array
.splice(0, 3)
// get first three values
.join()
// joining the 3 values
)
I suggest to iterate over the keys of the object and use the keys for reducing the values to the smallest value.
var z = {
"a": 4,
"b": 2,
"c": 5,
"d": 1,
"e": 3
},
smallest = Object.keys(z).reduce(function (r, k) {
return Math.min(r, z[k]);
}, Number.MAX_VALUE);
document.write(smallest);
Related
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 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I need the sum total of the object, where, but the maximum of each similar pair
javascript
var score = {
"work_1": 5,
"work_1|pm": 10,
"work_2": 8,
"work_2|pm": 7
"work_3": 10
};
the work_3 doesn't have a pair similar
I wish this result
total = 28
Group the maximums by key-prefix in a new object, and then sum the values of that object. In both phases you can use reduce:
var score = {
"work_1": 5,
"work_1|pm": 10,
"work_2": 8,
"work_2|pm": 7,
"work_3": 10
};
var result = Object.values(
Object.entries(score).reduce((acc, [k, v]) => {
k = k.split("|")[0];
acc[k] = Math.max(v, acc[k] ?? v);
return acc;
}, {})
).reduce((a, b) => a + b, 0);
console.log(result);
You can get the property values of the object with Object.values, sort the resulting array, then sum the first 2 items:
var score = {
"work_1": 5,
"work_1|pm": 10,
"work_2": 8,
"work_2|pm": 7,
"work_3": 10
};
const max2 = Object.values(score).sort().splice(0, 2)
const result = max2[0] + max2[1];
console.log(result)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have this initialArray = [1,2,3,4,5,6]
I want to add this [1,2,3]
1 / If [1,2,3] exists in the initialArray, I want to remove it from initialArray.
So the results will be [4,5,6]
2 / Then I want to add [1,2,3] again, and now [1,2,3] is not exist anymore in that initialArray.
So in that case, results will be [4,5,6,1,2,3]
3 / Now I want to add [1,2,3,4,5,6]. So in that case, results will be []
I tried to use .filter() to remove existing values, and it works. But I can't "concat" if values doesn't exist. I have not been able to do both.
How can I do?
You can use indexOf method, so it might look something like this (basic example to gave you an idea):
var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);
think about this also, code below will acctually check if the value you tried to insert to array exist allready inside, so it will remove it:
for(var i = arrayWithNumbers.length - 1; i >= 0; i--) {
if(arrayWithNumbers[i] === number) {
arrayWithNumbers.splice(i, 1);
}
}
You could iterate the array to add and seach for the index and ither push the value or splice the array.
This solution mutates the original array.
function add(target, source) {
source.forEach(v => {
var p = target.indexOf(v);
if (p === -1) {
target.push(v);
} else {
target.splice(p, 1);
}
});
return target;
}
var array = [1, 2, 3, 4, 5, 6];
add(array, [1, 2, 3]);
console.log(array); // [4, 5, 6]
add(array, [1, 2, 3]);
console.log(array); // [4, 5, 6, 1, 2, 3]
add(array, [1, 2, 3, 4, 5, 6]);
console.log(array); // []
const initialArray = []; // your initial array
const add = []; // stuff you want to add
const { filtered, toAdd } = initialArray.reduce((acc, curr) => {
const index = acc.toAdd.findIndex(v => v === curr);
index === -1 ? acc.filtered.push(curr) : acc.toAdd.splice(index, 1);
return acc;
}, { filtered: [], toAdd: [...add] });
const final = [...filtered, ...toAdd];
And if your initialArray had duplicate values you could just do,
const initialArray = [...new Set(initialArrayWithDuplicates)];
Another way of doing this, mutating the original array could be this:
const initialArray = [1,2,3,4,5,6];
const toggleElements = (array, change) =>
array.toString().includes(change)
? array.splice(array.indexOf(change[0]), change.length)
: array.push(...change);
toggleElements(initialArray, [1,2,3]);
console.log(initialArray);
toggleElements(initialArray, [1,2,3]);
console.log(initialArray);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i have an array like below
[1,2,'b',4 ,'a','b',5,'o',7,1,3,'p',9,'p']
I want to check that if the above array has three consecutive numbers in a sequence (i.e) [1,2,3].
From the above array i want the output as below given example
[7,1,3] - > Since this sequence is occuring in a sequence without getting blocked by a alphabet.
You could take a temporary array and fill it with found numbers. For any not found number, empty the array and check then the length. If it has the wanted length, push the array to the result set.
var array = [1, 2, 'b', 4, 'a', 'b', 5, 'o', 7, 1, 3, 'p', 9, 'p'],
three = array.reduce((temp => (r, v) => {
if (typeof v !== 'number') {
temp = [];
return r;
}
temp.push(v);
if (temp.length === 3) {
r.push(temp);
}
return r;
})([]), []);
console.log(three);
Here is a way to do this . Just iterate over array and count number of occurance of numbers. As soon as count becomes 3 you have your magic numbers otherwise reset all. As #Rup suggested.
var arr = [1,2,'b',4 ,'a','b',5,'o',7,1,3,'p',9,'p'];
var result = [];
var count = 0;
arr.forEach(function(element) {
if(typeof (element) == "number" ){
count +=1;
result.push(element)
}else {
if(count == 3){
console.log(result);
return ;
}else if(count < 3){
count = 0;
result= [];
}
}
});
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 7 years ago.
Improve this question
var array = [0, 1, 2, 3];
var numbers = [3, 6 ,2, 7];
I want to multiply each number in array with numbers without repetition of numbers from numbers
Fixed number for all index
var array = [0, 1, 2, 3];
array.map(
function(n){
return (n* number to be multiplied);
}
);
Different number for each index
var array = [0, 1, 2, 3], numberToBeMultiplied = [1,3,5,7];
array.map(
function(n, i){
return n * numberToBeMultiplied[i];
});
You can also push the returning elements in an array.
Your question is not clear enough, what I get you may want to do something like this.
var array = [1,2,3,4]
var array2 = [];
for(var i = 0; i < array.length; i++) {
var randomMultiplier = Math.floor((Math.random() * 10) + 1); //Return a random number between 1 and 10
array2.push(array[i] * randomMultiplier);
$('#multiplied-list').append('<li>'+array[i] * randomMultiplier+'</li>')
}
console.log(array2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="multiplied-list"></ul>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have an array of numbers and I need to find the maximum slice of the array which contains no more than two different numbers.
so if I have
[1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8]
the output I'm looking is 10, because the array slice of (0, 9) is the largest slice of the array with no more than two different numbers.
How do I achieve that?
This example does the trick for you. However I kindly ask other higher programming gods to improve this or provide another solution. I think this code could be greatly optimized. Please comment if you find bugs, or examples to which this function returns a faulty solution.
function returnLargestConsecutiveArraySlice(array)
{
//set an empty array.
var a = [];
//walk the supplied array and check if number is not repeated
array.filter(function (element, index, array) {
if (element != array[index-1] && element != array[index+1])
{
a.push(index);
return element;
}
}
);
//the returned array contains all indexes to the numbers that are not repeated.
//walk the array and check if number the next number matches the current one.
//If so the index is consecutive.
var numbers = a;
var b = [[]]; //use an empty array to start with.
var index = 0;
for (var i = 0; i < numbers.length-1; i++){
if(numbers[i+1] == numbers[i]+1)
{
//number is consecutive, add.
b[index].push(numbers[i]);
}
else
{
//chain broken, start a new one.
index++;
b[index] = [];
}
}
//we now have an array with all chains. Look for the largest chain.
var largest = [];
for (var i = 0; i < b.length; i++)
{
if (b[i].length > largest.length)
{
largest = b[i];
}
}
//largest chain found. Slice the original array on the largest chain.
return array.slice(largest[0], largest[0] + largest.length+1);
}
console.log(returnLargestConsecutiveArraySlice([1, 1, 1, 2, 2, 2, 4, 5, 6, 1, 1, 7, 8, 9, 10, 11, 2, 2, 6, 2, 1, 8]));