Created
September 19, 2011 01:37
-
-
Save ishiduca/1225819 to your computer and use it in GitHub Desktop.
配列をソートした場合の最初もしくは最後の値を参照する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// javascriptの配列でソートした結果を取得する場合 | |
// arrayORG.sort(); | |
// | |
// すると、元々の配列(arrayORG)がソートした並びに代えられてしまって具合が良くない場合がある。 | |
// arrayCOPY = arrayORG.sort(); | |
// | |
// みたいにできないので、そういう場合には | |
// arrayCOPY = arrayORG.slice(0).sort(); | |
// | |
// すると、arrayORGのコピーを作って、それをソートすることになるので、(コストは安くないけど) | |
// これを利用する。ソートされたコピー配列の最初か最後をもぐようにすればいいので、メソッド化しておく | |
// Array.first() と Array.last() | |
// | |
// んで、文字列の場合大文字小文字を区別したりしなかったりするオプションがほしいので、メソッドの引数に | |
// ソート順を定義する関数(compareFunction)を指定するように実装してみた | |
// var first = Array.first(compareFunction), | |
// last = Array .last(compareFunction); | |
if (! Array.prototype.last) { | |
Array.prototype.last = function (FuncOfSortRule) { | |
return this.slice(0).sort(FuncOfSortRule).pop(); | |
}; | |
} | |
if (! Array.prototype.first) { | |
Array.prototype.first = function (FuncOfSortRule) { | |
return this.slice(0).sort(FuncOfSortRule).shift(); | |
}; | |
} | |
function qw (str, cut) { | |
if (typeof str !== 'string') return undefined; | |
cut = cut || /\s+/; | |
cut = (typeof cut === 'string') ? new RegExp(cut) : cut; | |
return str.replace(/^\s*/, '').replace(/\s*$/, '').split(cut); | |
} | |
var sortRuleToString = function (a, b) { | |
a = a.toString().toLowerCase(); | |
b = b.toString().toLowerCase(); | |
return (a > b) ? 1 : | |
(b > a) ? -1 : 0; | |
} | |
var org = qw(" mak Nam gnr com All act "); | |
console.log('元の配列'); | |
console.log(JSON.stringify(org)); | |
console.log('\n配列を並び替えた場合、その最後の文字列。大文字小文字を区別する'); | |
var last = org.last(); | |
console.log(last); | |
console.log('\n配列を並び替えた場合、その最初の文字列。大文字小文字を区別する'); | |
var first = org.first(); | |
console.log(first); | |
console.log('\n配列を並び替えた場合、その最後の文字列。大文字小文字を区別しない'); | |
var last = org.last(sortRuleToString); | |
console.log(last); | |
console.log('\n配列を並び替えた場合、その最初の文字列。大文字小文字を区別しない'); | |
var first = org.first(sortRuleToString); | |
console.log(first); | |
console.log('\n元の配列は破壊されていない'); | |
console.log(JSON.stringify(org)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment