0

Как сравнить 2 массива при этом arr1 сортировался по position 1 , 2 и тд, arr2 добавить в конец arr1

arr2

  [{
    "id": 1, "name": "iphone", position: 0, "checked": false
  },{
    "id": 2, "name": "samsung", position: 0, "checked": false
  },{ 
    "id": 3, "name": "huawei", position: 0, "checked": false
  }]

arr1

 [{
   "id": 16, "name": "samsung", position: 2, "checked": true
 },{
   "id": 15, "name": "iphone", position: 1, "checked": true
 }] 

Результат

 [{
      "id": 15, "name": "iphone", position: 1, "checked": true
 },{
      "id": 16, "name": "samsung", position: 2, "checked": true
 },{
      "id": 1, "name": "iphone", position: 0, "checked": false
 },{
      "id": 2, "name": "samsung", position: 0, "checked": false
 },{ 
      "id": 3, "name": "huawei", position: 0, "checked": false
 }] 
2

2 ответа 2

2

ES6

const arr1 = [1,2,3]
const arr2 = [4,5,6]
const arr3 = [...arr1, ...arr2] //arr3 ==> [1,2,3,4,5,6]

Ну или https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

1

Не совсем понимаю, что в данном случае подразумевается под сравнением. Если нужно соединить два массива объектов, а первый при этом отсортировать по полю position, можно так (имейте в виду, что первый массив останется отсортированным — если это нежелательно, можно создать его копию перед сортировкой):

const arr1 = [
  { "id": 16, "name": "samsung", position: 2, "checked": true },
  { "id": 15, "name": "iphone", position: 1, "checked": true },
];

const arr2 =[
  { "id": 1, "name": "iphone", position: 0, "checked": false },
  { "id": 2, "name": "samsung", position: 0, "checked": false },
  { "id": 3, "name": "huawei", position: 0, "checked": false },
];

const result = arr1.sort((a, b) => a.position - b.position).concat(arr2);

console.log(result);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.