[英]Find the closest value in array by other array
I have an array 我有一个数组
var master = [0,2,4,6,8,10];
and i have another array 我还有另一个数组
var result = [4,5,6];
i need to filter the master array based on result array and it should return like the below 我需要根据结果数组过滤主数组,并且应该返回如下内容
var finalmaster = [2,4,6,8];
because 4,5,6 is bounds between 2 to 8 from master array 因为4,5,6在主数组中的边界在2到8之间
i tried something like below 我尝试了如下
var min = Math.min(result);
var max = Math.max(result);
var temp = [];
for(i=0;i<master.length;i++) {
if(master[i]>=min && master[i]<=max) {
temp.push(master[i]);
}
}
var temp = [4,6];
But i need the adjacent one value too the temp should look like 但是我也需要相邻的一个值,温度应该像
var temp = [2,4,6,8];
Can anyone suggest a dynamic solution for this ? 有人可以为此建议动态解决方案吗?
You could check if the previous element or the next element is included in the result set. 您可以检查结果集中是否包含上一个元素或下一个元素。
function getValues(master, values) { return master.filter( (m, i, a) => a.slice(Math.max(0, i - 1), i + 2).some(v => values.includes(v)) || values.some(v => v > a[i - 1] && v < m || v > m && v < a[i + 1]) ); } console.log(getValues([0, 2, 4, 6, 8, 10], [4, 5, 6])); console.log(getValues([0, 2, 4, 6, 8, 10], [5]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can try following 您可以尝试关注
var master = [0,2,4,6,8,10]; var result = [4,5,6]; master.sort((a,b) => ab); // Sort your array var temp = []; // find min and max of result var min = Math.min(...result); var max = Math.max(...result); for(i=0;i<master.length;i++) { var item = master[i]; if(item >= min && item <= max) { // if falls in range push temp.push(item); } else if (item < min) { // if less than min, always set to first in array temp[0] = item; } else if (item > max) { // if greater than than max, push to array and exit temp.push(item); break; } } console.log(temp);
Since you are expecting exactly 4 numbers that have specific positions you could get each one by index determined by their relation to each other. 因为您期望恰好有特定位置的4个数字,所以您可以通过索引来获得每个索引,索引由它们之间的关系决定。
const master = [0, 2, 4, 6, 8, 10]; const result = [4, 5, 6]; const arrayA = [0, 3, 6, 9, 12]; const array1 = [2, 4, 6, 8]; const arrayB = [1, 2, 3, 4, 5, 6, 7, 8]; const array2 = [5]; function getIndices(minor, major) { const merged = Array.from(new Set([...minor, ...major])).sort(function(a, b) { return a - b }); //console.log(merged); const min = minor[0]; const max = minor[minor.length - 1]; const prev = merged[merged.indexOf(min) - 1]; const next = merged[merged.indexOf(max) + 1]; const final = min === max ? [prev, min, next] : [prev, min, max, next]; return final; } console.log(`The indices of result and master are: [${getIndices(result, master)}]`); console.log(`The indices of array1 and arrayA are: [${getIndices(array1, arrayA)}]`); console.log(`The indices of array2 and arrayB are: [${getIndices(array2, arrayB)}]`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.