Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按特定顺序显示对象并重复_Javascript_Arrays - Fatal编程技术网

Javascript 按特定顺序显示对象并重复

Javascript 按特定顺序显示对象并重复,javascript,arrays,Javascript,Arrays,我有以下数组 [ { id: 1, type: "test1" }, { id: 2, type: "test1" }, { id: 3, type: "test2" }, { id:4, type: "test2" }, { id: 5, type: "test3" }, { id: 6 type: "test3" } ] 我需要按以下顺序显示项目(使用javascript) 先键入3,再键入1,再键入2,然后先重复键入test3,再重复键入test1,再重复键入test2 我得到一个对象数

我有以下数组

[ { id: 1, type: "test1" }, { id: 2, type: "test1" }, { id: 3, type: "test2" }, { id:4, type: "test2" }, { id: 5, type: "test3" }, { id: 6 type: "test3" } ]
我需要按以下顺序显示项目(使用javascript)

先键入3,再键入1,再键入2,然后先重复键入test3,再重复键入test1,再重复键入test2

我得到一个对象数组,每个对象都有一个type属性。如何有效地对数组进行排序,以便始终获得以下顺序:

类型3,类型1,类型2,然后类型3,类型1,类型2,然后重复。所以从本质上说,类型2总是在类型1之后,类型3总是在类型2之后或者在开始的时候

例如,上面的数组将导致项目按以下顺序显示:

身份证5,身份证1,身份证3,身份证6,身份证2,身份证4


我需要尽可能高效地执行此操作。

为什么不在对象中循环并搜索每种类型

// order of types to loop through
var order = ["test3", "test1", "test2"];

// your data set
var objects = [ { id: 1, type: "test1" }, { id: 2, type: "test1" }, { id: 3, type: "test2" }, { id:4, type: "test2" }, { id: 5, type: "test3" }, { id: 6, type: "test3" } ];

// array to put sorted values into
var sortedArray = [];

// loop through as many times as the number of objects
// i = loop iteration counter, j = index of words
for(var i = 0, j = 0; i < objects.length; i++, j++) {

    // j cycles through the possible types
    if(j == order.length)
        j = 0;

    // find the word that matches the current type
    for(var k = 0; k < objects.length; k++) {

        // if word has not been matched already and has the correct type ...
        if(order[j] == objects[k].type && sortedArray.indexOf(objects[k].id) < 0) {

            // add it to the output array and exit
            sortedArray.push(objects[k].id);
            break;
        }
    }
}

// sorted result stored in `sortedArray` variable
//要循环的类型顺序
变量顺序=[“test3”、“test1”、“test2”];
//您的数据集
var对象=[{id:1,类型:“test1”},{id:2,类型:“test1”},{id:3,类型:“test2”},{id:4,类型:“test2”},{id:5,类型:“test3”},{id:6,类型:“test3”}];
//要将排序后的值放入的数组
var-Darray=[];
//循环次数与对象数量相同
//i=循环迭代计数器,j=单词索引
对于(变量i=0,j=0;i

请参阅上的工作示例。

不如先尝试一下,然后再回来找我们!您的JSON在最后一个对象中有一个输入错误:它缺少一个逗号。