繁体   English   中英

在其他数组中找到最接近数组的值

[英]Find the closest value in array by other array

我有一个数组

var master = [0,2,4,6,8,10];

我还有另一个数组

var result = [4,5,6];

我需要根据结果数组过滤主数组,并且应该返回如下内容

var finalmaster = [2,4,6,8];

因为4,5,6在主数组中的边界在2到8之间

我尝试了如下

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];

但是我也需要相邻的一个值,温度应该像

var temp = [2,4,6,8];

有人可以为此建议动态解决方案吗?

您可以检查结果集中是否包含上一个元素或下一个元素。

 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; } 

您可以尝试关注

 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); 

因为您期望恰好有特定位置的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM