最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Break array into multiple arrays based on first character in values - Stack Overflow

programmeradmin2浏览0评论

I have the following javascript array:

var data = ["2_000001", "1_000001", "2_000002", "1_000002", "1_000003", "2_000003", "2_000004", "1_000004", "1_000005", "2_000005"]

How can I make 2 new arrays (or more if there are more elements with eg. 3_ or 4_ as identifier) like this:

var 2 = ["2_000001", "2_000002", "2_000003", "2_000004", "2_000005"]
var 1 = ["1_000001", "1_000002", "1_000003", "1_000004", "1_000005"]

I have so far:

data.forEach(function (str) {

    str_api = str.substring(0, str.indexOf('_'));
    console.log(str_api);
    a_api.push(str_api);
    clean_api = $.unique(a_api);

    str_id = str.substring(str.indexOf("_") + 1);
    console.log(str_id);

});

Its not really close to the goal yet. Any help wele!

I have the following javascript array:

var data = ["2_000001", "1_000001", "2_000002", "1_000002", "1_000003", "2_000003", "2_000004", "1_000004", "1_000005", "2_000005"]

How can I make 2 new arrays (or more if there are more elements with eg. 3_ or 4_ as identifier) like this:

var 2 = ["2_000001", "2_000002", "2_000003", "2_000004", "2_000005"]
var 1 = ["1_000001", "1_000002", "1_000003", "1_000004", "1_000005"]

I have so far:

data.forEach(function (str) {

    str_api = str.substring(0, str.indexOf('_'));
    console.log(str_api);
    a_api.push(str_api);
    clean_api = $.unique(a_api);

    str_id = str.substring(str.indexOf("_") + 1);
    console.log(str_id);

});

Its not really close to the goal yet. Any help wele!

Share Improve this question edited Nov 18, 2015 at 17:25 isherwood 61.2k16 gold badges121 silver badges170 bronze badges asked Nov 18, 2015 at 17:22 domi771domi771 4701 gold badge9 silver badges21 bronze badges 1
  • 1 You'll have a really bad time if you try to use numbers as identifiers, consider using an Array or Object instead if you need indicies – Paul S. Commented Nov 18, 2015 at 17:25
Add a ment  | 

3 Answers 3

Reset to default 3

Using an Arrow Function

var obj = {};
data.forEach((e, i) => (i = parseInt(e, 10), obj[i] ? obj[i].push(e) : (obj[i] = [e])));

obj;
/* {
    "1": ["1_000001","1_000002","1_000003","1_000004","1_000005"],
    "2": ["2_000001","2_000002","2_000003","2_000004","2_000005"]
} */
  • (e, i) => expr is a Function which takes two parameters, e and i (here we just want i scoped)
  • (expr1, expr2) is two expressions making use of the ma operator ,
  • expr1 ? expr2 : expr3 means if expr1 truthy, do expr2, otherwise do expr3

  • parseInt will truncate for us as _ is an invalid number character

  • arr.forEach applies a function to every item in an Array

Genrating variables on the go will not a be a good idea so either use a Object or Multi Dimensional Array

    var data = ["2_000001", "1_000001", "2_000002", "1_000002", "1_000003", "2_000003", "2_000004", "1_000004", "1_000005", "2_000005"];

    var arr = {};

    // Loop through array
    [].forEach.call(data, function(inst){

        var x = inst.split("_")[0];

        // Check if arr already has an index x, if yes then push
        if(arr.hasOwnProperty(x)) 
            arr[x].push(inst);

        // Or else create a new one with inst as the first element.
        else 
            arr[x] = [inst];


    });

Explanation of code is written as ments.

This will result in

{
    "2": ["2_000001", "2_000002", "2_000003", "2_000004", "2_000005"],

    "1": ["1_000001", "1_000002", "1_000003", "1_000004", "1_000005"]
}

Which you can use in anyway you want.

This creates an object with properties and the values you want.

var data = ["2_000001", "1_000001", "2_000002", "1_000002", "1_000003", "2_000003", "2_000004", "1_000004", "1_000005", "2_000005"];

// Initialize a new object
var arrays = {};

// Loop over data
data.forEach(function (str) {

    // Get id piece
    str_api = str.substring(0, str.indexOf('_') + 1);

    // check if existing property for this id, if not initialize new array
    if (!arrays[str_api]) {
        arrays[str_api] = [];
    }

    // get value piece
    str_id = str.substring(str.indexOf("_") + 1);

    // add to that id's array
    arrays[str_api].push(str_id);

});

console.log(arrays);

Fiddle: http://jsfiddle/AtheistP3ace/6e2bLgf5/

Output:

{
    2_: ["000001", "000002", "000003", "000004", "000005"],
    1_: ["000001", "000002", "000003", "000004", "000005"]
}

EDIT: Not sure if you want the underscore or not in the property name. In your description you give 3_ 4_ as examples but in code example you give 1 2.

发布评论

评论列表(0)

  1. 暂无评论