0

我有一个 mybooks 数组,我想将它按图书类别分开。

var mybooks = [
    ['novel','BookName1','$20.00'],
    ['novel','BookName2','$24.00'],
    ['novel','BookName3','$34.00'],
    ['novel','BookName4','$31.00'],
    ['novel','BookName4','$38.00'],
    ['Biograph','BookName5','$28.00'],
    ['Biograph','BookName6','$48.00'],
    ['Biograph','BookName7','$50.00']
  ];

我是这样弄的。

 for(i=0; i<mybooks.length; i++){
        if ((mybooks[i][0]) == 'novel'){
        var books = mybooks[i];
        console.log(books);
       }
      };

console.log(books) 打印

["novel", "BookName1", "$20.00"] 
["novel", "BookName2", "$24.00"]
["novel", "BookName3", "$34.00"]
["novel", "BookName4", "$31.00"] 
["novel", "BookName4", "$38.00"] 

如何使名为“拆分”的全局变量等于books

4

6 回答 6

2

制作一个函数返回书籍:

var makeBooks = function(mybooks, type){
  var books=[];
  for(var i=0; i<mybooks.length; i++){
      if ((mybooks[i][0]) === type){
        books.push(mybooks[i]);
      }
  };
  return books;
}

window.splitted = makeBooks(mybooks, 'novel');
于 2013-08-26T01:58:43.557 回答
1

一个相当简单的方法是:

var splitted = mybooks.filter(function(book) {return book[0] == 'novel';});

你可以这样概括它:

var byType = function(type) {return function(book) {return book[0] == type;};};
var bios = mybooks.filter(byType('Biograph'));
于 2013-08-26T02:11:42.387 回答
1

好吧,我不确定你想要的最终结果是什么,但你可以这样做:

var splitted = mybooks.reduce(function (result, book) {
    var cat = book[0];

    if (!result[cat]) {
        result[cat] = [book];
    } else {
        result[cat].push(book);
    }

    return result;
}, {});

console.log(splitted); //all books splitted by categories
console.log(splitted.novel); //array of novels
console.log(splitted.Biograph); //array of Biograph

如果您只是想一次收集一个类别,您也可以使用该filter功能。

var novels = mybooks.filter(function (book) {
    return book[0] === 'novel';
});
于 2013-08-26T02:05:43.307 回答
1
var splitted=$.grep(mybooks,function(o){return (o[0]=='novel');});
于 2013-08-26T02:06:55.380 回答
0

您是否尝试按书籍类别拆分数组?如果是这样,最好看看对象文字

于 2013-08-26T02:02:18.730 回答
0

这应该按类型排列您的书籍数组:

var mybooks = [
    ['novel','BookName1','$20.00'],
    ['novel','BookName2','$24.00'],
    ['novel','BookName3','$34.00'],
    ['novel','BookName4','$31.00'],
    ['novel','BookName4','$38.00'],
    ['Biograph','BookName5','$28.00'],
    ['Biograph','BookName6','$48.00'],
    ['Biograph','BookName7','$50.00']
  ];

var library = {}

for(i=0; i<mybooks.length; i++){
    var bookType = mybooks[i][0];
    if (typeof library[bookType]=='undefined')  
       library[bookType] = [];
    library[bookType].push(mybooks[i]);
}

console.log(library);
于 2013-08-26T02:13:59.137 回答