Как переупорядочить несколько элементов в массиве? - PullRequest
2 голосов
/ 01 ноября 2019

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

arr = [0,1,2,3,4,5]

Как переупорядочить / сместить несколько элементов? Например,

  • Я хочу удалить 0,2 and 3 и поместить их в индекс 4 так, чтобы конечный массив был [1,0,2,3,4,5]

В приведенном выше примере индекс4 с точки зрения исходного массива, а не конечного массива.

Я попытался использовать сплайс, как это:

items = [0,2,3] // items to be reordered
indexes = [0,2,3] // get their indexes
arr = [...arr.filter((it)=> !indexes.includes(arr.indexOf(it)))]
arr.splice(4, 0, ...items)
// result [1, 4, 5, 0, 2, 3]

Выше не является ожидаемым результатом

Ответы [ 4 ]

3 голосов
/ 01 ноября 2019

Это решение изменяет массив.

Вы можете сохранить значение в позиции вставки, удалить элементы и склеить удаленные элементы после индекса сохраненного элемента.

position             v
index    0  1  2  3  4
array   [0, 1, 2, 3, 4, 5]              store value at index
            1        4  5               rest array after removing items
            1        4 [0  2  3] 5      splice with removed items

var array = [0, 1, 2, 3, 4, 5],
    remove = [0, 2, 3],
    insertAtIndex = 4,
    valueAtPosition = array[insertAtIndex];
    
remove.forEach(v => array.splice(array.indexOf(v), 1));
array.splice(array.indexOf(valueAtPosition) + 1, 0, ...remove);

console.log(...array);
2 голосов
/ 01 ноября 2019

const temp = [0, 2, 3];
const arr = [0, 1, 2, 3, 4, 5];
const index = arr[4];

// Accepts an array (temp) and returns a function to be used
// as the callback for `filter` which accepts an element
// and returns whether that element is in the temp array
const filterUsing = (arr) => (el) => !arr.includes(el);

// `filter` the elements from the main array
const filtered = arr.filter(filterUsing(temp));

// Find the new position of the element in `index`
const newIndex = filtered.findIndex(el => el === index);

// Splice in the temp array back into the filtered array
filtered.splice(newIndex, 0, ...temp);

console.log(filtered);
2 голосов
/ 01 ноября 2019

Попробуйте использовать этот подход:

let arr = [0,1,2,3,4,5];
let rmv = [0, 2, 3];

const remove = (src, rem, i ) => {
  const arrWithIndexes = src.map((a, i) => { return  {value: a, index: i}});
  const filtered = arrWithIndexes.filter(f => !rem.some(s=> s === f.value));
  const indexToInsert = filtered.findIndex(f=>f.index === i);
  const result = filtered.map(f=> f.value);
  result.splice(indexToInsert, 0, ...rem);
  console.log(result);
}

console.log(remove(arr, rmv, 4));

Или, если вы знаете нужный индекс:

let arr = [0,1,2,3,4,5];
let rmv = [0, 2, 3];

const remove = (src, rem ) => {
  const filtered = src.filter(f=> !rem.some(s=> s === f));
  filtered.splice(2, 0, ...rmv)
  console.log(filtered);

}

console.log(remove(arr, rmv));
2 голосов
/ 01 ноября 2019

Вы можете сначала удалить данные элементы, а затем использовать splice(), чтобы добавить их по необходимому индексу.

function shiftElementsTo(arr, inds, final){
   let set = new Set(inds);
   let removed = inds.map(x => arr[x]);
   arr = arr.filter((x, i) => !set.has(i));
   arr.splice(final, 0, ...removed);
   return arr;
}

console.log(shiftElementsTo([0, 1, 2, 3, 4, 5], [0, 2, 3], 2))
...