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.
Improve this question
This seems like a very straightforward problem but for the life of me, I can not get it sorted.
I want to compare two arrays and if the value of array2 is in array1 push it to a new array otherwise push a 0.
these are my arrays:
let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let arrayTwo = [3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16];
desired outcome is
[0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]
current attempt with obvious indices issues
let newArray = [];
for (let i=0; i < arrayOne.length; i++){
if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);
else newArray.push(0);
};
current result
[0, 0, 0, 8, 9, 10, 0, 0, 13, 14, 15, 16, undefined, undefined, undefined, undefined, undefined, 0]
Issue with your approach is that you are searching for an index in arrayTwo
if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);
where i is the index not a value. That's why you are getting undefined values, because arrayTwo has less values then arrayOne, so index of arrayOne will not exists in arrayTwo.
Instead you should search for value in arrayTwo
for (let i=0; i < arrayOne.length; i++){
let value = arrayOne[i];
if(arrayTwo.includes(value)) newArray.push(value);
else newArray.push(0);
};
If you check only for existence of the value in collection - use Set which designed exactly for this purpose.
let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let values = new Set([3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16]);
const result = arrayOne.map(value => values.has(value) ? value : 0);
// => [0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]
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 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
x = [1, 2, 3, 4]
t = []
c = []
for(i = 0; i<x.length; i++){
function solution(){
t = Math.pow(x, 2)
c = t[i]++
return c
}
}
The function needs to:
Count the squares of the array numbers
Then to get sum of squared (I am not sure if I wrote it correct, LOL) numbers. Thanks!
const result = [1, 2, 3, 4].map(n => n ** 2).reduce((acc, val) => acc + val, 0);
console.log(result);
You can also use ** operator which is faster than Math.pow(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
var result = [1, 2, 3, 4].map(n => Math.pow(n, 2)).reduce((acc, val) => acc + val, 0);
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
Input
Array =[4,2,8,11,14,6,1]
Expectedtotal=20
Output
[2,4,6,8], [11,8,1],[6,11,1,2],[2,14,4],[14,6]
code:
const arr = [4, 2, 8, 11, 14, 6, 1];
const target = 20;
res = _.filter(arr, v => _.filter(arr, v1 => _.filter(arr, v2 => _.filter(arr, v3 => v + v1 + v2 + v3 === target))); console.log(res);
I am the beginner of javascript and lodash. I tried this code by own..please help me to write good code.
You could use a temporary array and the index and iterate the next index by either taking the actual value or not.
function subsetSum(array, sum) {
function iter(index, temp, s) {
if (s === sum) return result.push(temp.slice()); // exit sum found
if (index >= array.length) return; // exit index over
iter(index + 1, temp.concat(array[index]), s + array[index]); // take value
iter(index + 1, temp, s); // omit value
}
var result = [];
iter(0, [], 0);
return result;
}
console.log(subsetSum([4, 2, 8, 11, 14, 6, 1], 20).map(a => a.join(' ')));
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
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.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I have a JSON dataset,
{
"a": ["73.0", "41.0", "98.0", "43.0"],
"s": ["74.0", "43.0", "112.0", "44.0"],
"f": ["75.0", "45.0", "116.0", "45.0"],
"l": ["76.0", "47.0", "120.0", "46.0"],
"x": ["77.0", "49.0", "128.0", "47.0"],
"q": ["78.0", "51.0", "134.0", "48.0"]
}
I want to closest match with a test data e.g. below, closest match is the array in the dataset which has lowest average difference related to the test array. In this example the closest match is "a": ["73.0", "41.0", "98.0", "43.0"],
{
"t": ["75.0", "42.0", "100.0", "44.0"]
}
Any library which can help with this? btw doing in JS.
This answer is based on the assumption that:
Your json is parsed and normalized so that all array values are numbers
You intend to measure difference in absolute numbers: diff(a, b) => Math.abs(a - b)
You want to find the key of the property pointing to the array that matches closest
// We're gonna get the closest match from here
const parsedJson = {
a: [73, 41, 98, 43],
s: [74, 43, 112, 44],
f: [75, 45, 116, 45],
l: [76, 47, 120, 46],
x: [77, 49, 128, 47],
q: [78, 51, 134, 48],
};
// We're gonna find the closest match to this
const comparator = [75, 42, 100, 44];
// Gets the average value of all given numbers
const avg = (...numbers) => numbers.reduce((acc, n) => acc + n, 0) / numbers.length;
// Returns an array with the absolute numeric difference
// between corresponding indices within 2 given arrays of
// numbers.
const difference = (arr1, arr2) => arr1.map((num, i) => Math.abs(num - arr2[i]));
// Returns the key of source that contains the array that
// matches closest to predicate.
const closestMatch = (comparator, source) => {
const [keyOfClosestMatch] = Object
.keys(source)
.map(key => [key, avg(...difference(comparator, source[key]))] )
.reduce((lowestSoFar, nextPredicate) => {
return lowestSoFar[1] < nextPredicate[1]
? lowestSoFar
: nextPredicate;
});
return keyOfClosestMatch;
}
let closestKey = closestMatch(comparator, parsedJson);
document.body.innerText = `Closest: "${closestKey}": [${parsedJson[closestKey]}]`;
You could iterate the keys and the items and check the absolute difference for taking the closest value for the result array.
var data = { a: ["73.0", "41.0", "98.0", "43.0"], s: ["74.0", "43.0", "112.0", "44.0"], f: ["75.0", "45.0", "116.0", "45.0"], l: ["76.0", "47.0", "120.0", "46.0"], x: ["77.0", "49.0", "128.0", "47.0"], q: ["78.0", "51.0", "134.0", "48.0"] },
test = ["75.0", "42.0", "100.0", "44.0"],
result = Object.keys(data).reduce(function (r, k, j) {
data[k].forEach(function (a, i) {
if (!j || Math.abs(a - test[i]) < Math.abs(r[i] - test[i])) {
r[i] = a;
}
});
return r;
}, []);
console.log(result);