Найти ближайшее значение в массиве по другому массиву

1

У меня есть массив

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

Но мне нужно смежное одно значение, и temp должен выглядеть так:

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

Может ли кто-нибудь предложить динамическое решение для этого?

  • 0
    почему 2 и 8 включены в новый массив?
  • 0
    @NinaScholz NinaScholz Я рисую график, поэтому мне нужно немного места на главной оси.
Теги:
arrays

3 ответа

1
Лучший ответ

Вы можете проверить, включен ли предыдущий элемент или следующий элемент в результирующий набор.

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; }
  • 0
    Я сомневаюсь, что это не удастся, если результат [5] и ожидаемый результат будет [4,6] , однако, с выше это будет пустой массив.
  • 0
    @NikhilAggarwal, пожалуйста, смотрите редактирование.
Показать ещё 1 комментарий
1

Вы можете попробовать следующее

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

master.sort((a,b) => a-b); // 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);
1

Поскольку вы ожидаете ровно 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)}]');

Ещё вопросы

Сообщество Overcoder
Наверх
Меню