Reputation: 25
how to merge the value or merge the index,
for example I have :
var input = [
["0001", "Roman Alamsyah", "Bandar Lampung", "21/05/1989", "Membaca"],
["0002", "Dika Sembiring", "Medan", "10/10/1992", "Bermain Gitar"],
];
and I want my array to be
var output = [
["0001", "Roman Alamsyah", "Bandar Lampung 21/05/1989", "Membaca"],
["0002", "Dika Sembiring", "Medan 10/10/1992", "Bermain Gitar"]
];
thanks
Upvotes: 2
Views: 146
Reputation: 4246
You might use destructuring assignment :
[a,b,c,d] = [1,2,3,4];
var mergedArr = [a,+(""+b+c),d];
console.log(mergedArr);
In this way you can treat each array-element as variable at a certain index. After that you can merge each variable as you like.
It must be mentioned that this operator is not supported by all browsers yet.
Addition to updated question:
You can also implement a function that recursively merges array-elements at a given start- and end-index. In this resurive way you can merge sub-arrays as well.
var input = [
['0001',
'Roman Alamsyah',
'Bandar Lampung',
'21/05/1989',
'Membaca'],
[
'0002',
'Dika Sembiring',
'Medan',
'10/10/1992',
'Bermain Gitar'
],
];
var input2 = [
[
['0001',
'Roman Alamsyah',
'Bandar Lampung',
'21/05/1989',
'Membaca']
],
[
'0002',
'Dika Sembiring',
'Medan',
'10/10/1992',
'Bermain Gitar'
],
];
function mergeValues(arr, start, end) {
if (arr.__proto__.constructor === Array && arr[0].__proto__.constructor !== Array) {
var mergedValues = [];
var result = [];
arr.forEach(function (value, index) {
if (index < start) result.push(value);
else if (index > end) {
if (mergedValues.length) {
result.push(mergedValues.join(' '));
mergedValues = [];
}
result.push(value);
}
else mergedValues.push(value);
});
return result;
}
else {
return arr.map(function (subarr) {
return mergeValues(subarr, start, end);
});
}
}
console.log("input: ",mergeValues(input, 2, 3));
console.log("input2: ",mergeValues(input2, 2, 3));
Hope this helps.
Upvotes: 1
Reputation: 386560
You could specify the index joinAt
, where the next two elements has to be joined and then splice the array with a new string of the spliced parts.
var array = [
["0001", "Roman Alamsyah", "Bandar Lampung", "21/05/1989", "Membaca"],
["0002", "Dika Sembiring", "Medan", "10/10/1992", "Bermain Gitar"],
],
joinAt = 2;
array.forEach(function (a) {
a.splice(joinAt, 0, a.splice(joinAt, 2).join(' '));
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 347
Not sure if this is what you want, but it produces the output asked for in the question:
[1,2,3,4].reduce(
(accumulator, currentValue, currentIndex, array) => {
(currentIndex !== 1 && currentIndex !== 2)
? accumulator.push(currentValue)
: currentIndex === 1
? accumulator.push(
Number.parseInt(
array[currentIndex].toString()
+ array[currentIndex + 1].toString()
)
)
: undefined ;
return accumulator ;
}
, []
)
See: Array.prototype.reduce() on MDN
Upvotes: 0