根据参考数组重新排序数组

时间:2017-02-23 09:21:18

标签: javascript arrays

const ids = ["first", "second", "third", "fourth", "fifth", "sixth"];

const items = [
  {id: "third", value: ".."},
  {id: "fifth", value: ".."},
  {id: "first", value: ".."},
  {id: "fourth", value: ".."}
];

正如您所看到的,订购方式不同,缺少secondsixth的商品。

  • items中的项目必须与ids
  • 中的项目顺序相同
  • 必须有null而不是遗失的项目(secondsixth

最终结果如下:

const items = [
  {id: "first", value: ".."},
  null, // <-- important
  {id: "third", value: ".."},
  {id: "fourth", value: ".."},
  {id: "fifth", value: ".."},
  null  // <-- important
];

这是一项性能关键功能,我需要它尽可能好地执行。

我有什么可以做的吗?以下表现统计中的那些数字都是可能的情况。

我的功能:

console.time('generate');
const arrays = generateArrays(100); // num of items, check perf stats below snippet

console.time('reorder');
reOrder(arrays.ids, arrays.items);


// THIS function is the purpose of this question
function reOrder(ids, items) {
  let result = [];

  ids.forEach((id, i) => {
    const match = items.find((item) => {
      return item.id === id;
    });

    // Missing, insert null instead
    if (match === undefined) {
       return result[i] = null;
    }
    // Has match, insert to proper index
    return result[i] = match;
  });

  console.timeEnd('reorder');
  console.log('final result:', result);
}


// Generate huge random arrays ([ids], [items])
// * Random items are missing 
// * Items are randomly shuffled
function generateArrays(count) {
  let ids = [];
  let items = [];
  let itemsIndex = 0;

  for(let i = 0; i < count; i++) {
    const randomID = Math.random().toString(36).substr(7);
    // Ids have beautiful full array without shenanigans
    ids[i] = randomID;

    // Randomly add items (a.k.a random items are missing)
    if (Math.random() < 0.7) {
      items[itemsIndex] = {
        id: randomID,
        idIndex: i, // to check if final result is correct
        itemIndex: itemsIndex, // to check if shuffled properly
        value: Math.random().toString(36).substr(7)
      };

      itemsIndex++;
    }
  }
  
  shuffleArray(items);
  
  //console.log('generated ids:', ids);
  //console.log('generated items:', items);
  console.timeEnd('generate');

  return {ids: ids, items: items};
}


// Shuffle items in array
function shuffleArray(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}

// Performance stats with my okay PC
--------------------------------------
       Count     |       Time
--------------------------------------
       100             0.3 - 1ms
       500              5 - 10ms
        1K             10 - 25ms

// WARNING, gets messy for weak rigs!

        5K            around 300ms
       10K              1 - 1.5s

2 个答案:

答案 0 :(得分:1)

您可以使用map()并创建新阵列。

const ids = ["first", "second", "third", "fourth", "fifth", "sixth"];

const items = [
  {id: "third", value: ".."},
  {id: "fifth", value: ".."},
  {id: "first", value: ".."},
  {id: "fourth", value: ".."}
];

var result = ids.map(function(e) {
  var obj = items.find(a => a.id == e);
  return obj ? obj : null
})

console.log(result)

您还可以创建哈希表并将其用于排序,而不是find

const ids = ["first", "second", "third", "fourth", "fifth", "sixth"];

const items = [
  {id: "third", value: ".."},
  {id: "fifth", value: ".."},
  {id: "first", value: ".."},
  {id: "fourth", value: ".."}
];

var hash = items.reduce((r, e) => (r[e.id] = e, r), {})
var result = ids.map(e => hash[e] ? hash[e] : null)
console.log(result)

答案 1 :(得分:1)

您可以使用

let result = Array(ids.length).fill(null);
items.forEach((item) => result[ids.indexOf(item.id)] = item);

用于对具有所需长度和null值的新数组进行gerating,并将实际项目分配到所需的插槽。

console.time('generate');
const arrays = generateArrays(100); // num of items, check perf stats below snippet

console.time('reorder');
reOrder(arrays.ids, arrays.items);

function reOrder(ids, items) {
    let result = Array(ids.length).fill(null);
    items.forEach((item) => result[ids.indexOf(item.id)] = item);
    console.timeEnd('reorder');
    console.log('final result:', result);
}


// Generate huge random arrays ([ids], [items])
// * Random items are missing 
// * Items are randomly shuffled
function generateArrays(count) {
    let ids = [];
    let items = [];
    let itemsIndex = 0;

    for(let i = 0; i < count; i++) {
        const randomID = Math.random().toString(36).substr(7);
        // Ids have beautiful full array without shenanigans
        ids[i] = randomID;

        // Randomly add items (a.k.a random items are missing)
        if (Math.random() < 0.7) {
            items[itemsIndex] = {
                id: randomID,
                idIndex: i, // to check if final result is correct
                itemIndex: itemsIndex, // to check if shuffled properly
                value: Math.random().toString(36).substr(7)
            };
            itemsIndex++;
        }
    }
  
    shuffleArray(items);
  
    console.timeEnd('generate');
    return {ids: ids, items: items};
}


// Shuffle items in array
function shuffleArray(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}
.as-console-wrapper { max-height: 100% !important; top: 0; }