我有以下JavaScript对象数组:
[{name: '4 Arn', isLetter: false},
{name: 'Abax', isLetter: false},
{name: 'Aramex', isLetter: false},
{name: 'Booking', isLetter: false},
{name: 'Dangerous', isLetter: false},
{name: 'Manali', isLetter: false}]
在上面的数组中,我想检查每个项目的name
属性的第一个字母。如果匹配,我想在对象之前追加一个新对象,如以下示例所示:
[{letter: "#", isLetter: true}, // new object
{name: '4 Arn', isLetter: false},
{letter: "A", isLetter: true}, // new Object
{name: 'Abax', isLetter: false},
{name: 'Aramex', isLetter: false},
{letter: "B", isLetter: true}, // new object
{name: 'Booking', isLetter: false},
{letter: "D", isLetter: true}, // new object
{name: 'Dangerous', isLetter: false},
{letter: "M", isLetter: true}, // new object
{name: 'Manali', isLetter: false}]
我尝试了reduce()
功能,但我不明白为什么它会给我错误的结果:
var newArr = [];
list.reduce(function(prev, cur, index, originalArrray) {
var previousCharcode = prev.name.toUpperCase().charCodeAt(0);
currentCharCode = cur.name.toUpperCase().charCodeAt(0);
newArr.push(prev);
if(previousCharcode != currentCharCode) {
newArr.splice(index, 0, {isLetter: true, letter: String.fromCharCode(currentCharCode)});
}
return cur;
});
答案 0 :(得分:4)
至少有两个原因导致您的代码无法提供预期的结果:
您使用的索引指向原始数组中的索引。由于您的新数组将包含更多元素,因此在新数组上使用该索引作为def find_all_from_source(source_id)
joins, conditions = invoke_records_from_source(source_id)
find(:all, :select => “#{self.table_name}”, :joins => joins, :conditions => conditions).each do |record|
yield record
end
end
result = {}
model.find_all_from_source(source_id) do |r|
result[r.id] = {'attribute' => r.attribute }
end
是没有意义的。它最终将指向错误的地方;
您只推送splice
元素,因此最后一个元素永远不会被推送到结果数组
我建议使用prev
积累值(回调的第一个参数)来构建最终数组。为了记住引入的最后一个字母对象,我将这个累积值与该字母配对。所以我将使用包含两个元素的数组:
然后最终结果将取自该数组的第一个元素,忽略第二个值。
我建议不要使用字符代码,而只使用字符。它可以帮助您避免将代码转换回字符。
以下是代码:
reduce
答案 1 :(得分:1)
检查此解决方案。迭代数组并将其附加到新数组。
var names = [{
name: '4 Arn',
isLetter: false
}, {
name: 'Abax',
isLetter: false
}, {
name: 'Aramex',
isLetter: false
}, {
name: 'Booking',
isLetter: false
}, {
name: 'Dangerous',
isLetter: false
}, {
name: 'Manali',
isLetter: false
}];
var newNames = [];
for (var i in names) {
var char = names[i].name.substring(0, 1);
var isNumber = !isNaN(char);
var entry = {
letter: (isNumber ? '#' : char.toUpperCase()),
isLetter: isNumber
};
newNames.push(entry);
newNames.push(names[i]);
}
console.log(newNames);
答案 2 :(得分:1)
使用这种方法可以解决问题
var list = [{name: '4 Arn', isLetter: false},
{name: 'Abax', isLetter: false},
{name: 'Aramex', isLetter: false},
{name: 'Booking', isLetter: false},
{name: 'Dangerous', isLetter: false},
{name: 'Manali', isLetter: false}];
var listResult = [];
list.map(function(item, index) {
if(index > 0) {
var currentCharcode = item.name.toUpperCase().charCodeAt(0);
var previousCharcode = list[index-1].name.toUpperCase().charCodeAt(0);
if(previousCharcode != currentCharcode) {
listResult.push({isLetter: true, letter: String.fromCharCode(currentCharcode)});
}
} else {
listResult.push({isLetter: true, letter: String.fromCharCode(currentCharcode)});
}
listResult.push(item);
});
console.log(JSON.stringify(listResult));
答案 3 :(得分:1)
我想你也可以用这样的功能方式做;
var arr = [{name: '4 Arn', isLetter: false},
{name: 'Abax', isLetter: false},
{name: 'Aramex', isLetter: false},
{name: 'Booking', isLetter: false},
{name: 'Dangerous', isLetter: false},
{name: 'Manali', isLetter: false}],
table = arr.reduce((p,c) => {var firstLetter = c.name[0];
isNaN(+firstLetter) ? p[firstLetter] ? p[firstLetter].push(c)
: p[firstLetter] = [c]
: p["#"] ? p["#"].push(c)
: p["#"] = [c];
return p;
},{}),
result = Object.keys(table).reduce((p,k) => p.concat({letter: k, isLetter: true},table[k]),[]);
console.log(result);
提示:+“A”返回NaN但+“4”返回4作为数字。所以isNaN()
是检查类型的非常有用的函数。
这是带有传统功能而不是箭头的版本;
var arr = [{name: '4 Arn', isLetter: false},
{name: 'Abax', isLetter: false},
{name: 'Aramex', isLetter: false},
{name: 'Booking', isLetter: false},
{name: 'Dangerous', isLetter: false},
{name: 'Manali', isLetter: false}],
table = arr.reduce(function(p,c){
var firstLetter = c.name[0];
isNaN(+firstLetter) ? p[firstLetter] ? p[firstLetter].push(c)
: p[firstLetter] = [c]
: p["#"] ? p["#"].push(c)
: p["#"] = [c];
return p;
},{}),
result = Object.keys(table).reduce(function(p,k){
return p.concat({letter: k, isLetter: true},table[k]);
},[]);
console.log(result);