This question already has answers here:
How to insert an item into an array at a specific index (JavaScript)
(28 answers)
Closed 3 years ago.
I already see the lodash documentation but I don't know what function do I need to use to solve my problem. I have array
const arr = [
{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name: 'jake'},
{name: 'baki'}
]
I want to add {name: 'ace'} before saske. I know about splice in javascript, but I want to know if this is possible in lodash.
Currently lodash not have that. You can use this alternate
arr.splice(index, 0, item);
const arr = [
{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name: 'jake'},
{name: 'baki'}
]
arr.splice(2, 0, {name: 'ace'})
console.log(arr)
You can try something like this:
const arr = [{
name: 'john'
},
{
name: 'jane'
},
{
name: 'saske'
},
{
name: 'jake'
},
{
name: 'baki'
}
]
const insert = (arr, index, newItem) => [
...arr.slice(0, index),
newItem,
...arr.slice(index)
];
const newArr = insert(arr, 2, {
name: 'ace'
});
console.log(newArr);
There is no support of such functionality in lodash : see issue.
If you still want it to look like done with lodash, then you can do it like this way.
fields = [{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name: 'jake'},
{name: 'baki'}
];
_.insert = function (arr, index, item) {
arr.splice(index, 0, item);
};
_.insert(fields,2,{'name':'ace'});
console.log(fields);
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Given two arrays of the same length and identical content, how can one sort an array to be the in same order as the second array, based on a shared property?
Example:
let array1 = [{id: 123, ...}, {id: 456, ...}, {id: 789, ...}] // order always stays the same
let array2 = [{id: 456, ...}, {id: 789, ...}, {id: 123, ...}] // order is always different
How can I sort array1 such that:
array1[0].id is 456 and
array2[0].id is 456
Loop through the first and push to the second by index:
let arr1 = [{id: 123}, {id: 456}, {id: 789}] // order always stays the same
let arr2 = [{id: 456}, {id: 789}, {id: 123}]
arr1.forEach((obj1, idx) => {
arr2[idx] = obj1
})
console.log(arr1, arr2)
Assuming array2 has the objects we care about and array1 specifies the order, map over the ordering array using it to select the objects to be ordered...
let array1 = [{id: 123 }, {id: 456 }, {id: 789, }]
let array2 = [{id: 456, name: '456' }, {id: 789, name: '789' }, {id: 123, name: '123' }]
let array2ElementsSortedByArray1 = array1.map(e => {
return array2.find(e2 => e2.id === e.id)
})
console.log(array2ElementsSortedByArray1)
You can create a hash of the shape {id: index, ...} from array2 and then use this to order the elements of array1. This saves you the cost of find() on each iteration.
let array1 = [{ id: 123, }, { id: 456, }, { id: 789, }] // order always stays the same
let array2 = [{ id: 456, }, { id: 789, }, { id: 123, }]
const
indeces = Object.fromEntries(array2.map(({ id }, i) => [id, i])), // { 456: 0, 789: 1, 123: 2 }
ordered = [];
array1.forEach(o => ordered[indeces[o.id]] = { ...o });
console.log(ordered)
I have this array:
sampleArray = [
{name: 'product-2'},
{name: 'product-15'},
{name: 'product-3'},
{name: 'product-10'}
]
I want to sort it using the property name, alphabetically except for numbers inside the strings.
I am using sort combined with localeCompare:
sampleArray.sort((a, b) => a.name.localeCompare(b.name))
However, as name is a string that contains a number I am getting this:
sampleArray = [
{name: 'product-10'},
{name: 'product-15'},
{name: 'product-2'},
{name: 'product-3'}
]
I need to get it in the correct order considering the numbers as well. What would be this:
sampleArray = [
{name: 'product-2'},
{name: 'product-3'},
{name: 'product-10'},
{name: 'product-15'}
]
I know if I was working only with numbers I could do that:
sampleArray.sort((a,b) => a - b)
But that's not the case.
How can I solve this?
You was half way, String#localeCompare accepts an option where you can use a natural sorting with strings.
const
array = [{ name: 'product-2' }, { name: 'product-15' }, { name: 'product-3' }, { name: 'product-10' }];
array.sort((a, b) => a.name.localeCompare(
b.name,
undefined,
{ numeric: true, sensitivity: 'base' }
));
console.log(array);
This question already has answers here:
Extract certain properties from all objects in array
(5 answers)
Closed 4 months ago.
How to filter an array of objects with a condition and return only specific properties of filtered objects?
I know we can use filter followed by map to achieve this. But I am looking for more simple solution.
For ex:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
Suppose if I want only ids of name "lala".
Output should be,
[{id: 1}, {id: 3}]
The next simplest would be reduce
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}];
console.log(
arr.reduce((values, value) =>
{
if (value.name === 'lala') values.push({ id: value.id });
return values;
}, [])
);
You can simply use Array.prototype.reduce to combine both mapping and filtering in the same operation. If you want to make it super concise, you can use object destructuring in the second argument of the reduce callback:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}];
let filteredMappedArr = arr.reduce((acc, { name, id }) => {
if (name === 'lala')
acc.push({ id });
return acc;
}, []);
console.log(filteredMappedArr);
filter followed by map is probably the most readable solution, but if you're looking to do it all in one step, you're looking at the classic for loop or using reduce.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You can do it by using filter and map;
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
let res = arr.filter(item => item.id % 2 === 1).map(item => ({id: item.id}))
console.log(res);
You could take Array#flatMap and return either a new obejct or an empty array which has no value for flattening.
let array = [{ name: "lala", id: 1 }, { name: "coco", id: 2 }, { name: "lala", id: 3 }],
result = array.flatMap(({ id, name }) => name === 'lala' ? [{ id }] : []);
console.log(result);
using .filter() and .map() functions:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
let newArr = arr.filter((elm) => (elm.name === 'lala')).map( (elm) => {return {id:elm.id}});
console.log(newArr);
let arr = [
{ name: "lala", id: 1 },
{ name: "coco", id: 2 },
{ name: "lala", id: 3 },
];
let a = [];
arr.filter(({ name, id }) => {
if (name === "lala") {
a.push({ id });
}
});
console.log(a);
with filter we check for the condition where name matches 'lala' if yes then we push id to new array...that's simple
I have an array of objects that looks like this:
var countries = [
{id: SWE, value: 5},
{id: DE, value:10},
{id: SWE, anotherValue: 11},
{id: DE, anotherValue: 15}
]
I want to merge array elements by id. The result should look like this:
countries = [
{id: SWE, value: 5, anotherValue: 11},
{id: DE, value:10, anotherValue:15}
]
Right now, I'm doing this with a for loop and a lot of if and else.
Question: is there any (more elegant) javascript inbuilt functionality to achieve this?
I've tried googling this, the problem is that I'm not sure what to Google for (I'm a javascript newby). Any help is appreciated.
try this:
function mergeById(a){
var obj={};
a.forEach(function(e){
if(e && e.id){
obj[e.id] = obj[e.id] || {};
for(var _k in e) obj[e.id][_k] = e[_k]
}
});
return Object.keys(obj).map(function (key) {return obj[key]});
}
var countries = [
{id: 'SWE', value: 5},
{id: 'DE', value:10},
{id: 'SWE', anotherValue: 11},
{id: 'DE', anotherValue: 15}
]
document.write(JSON.stringify(mergeById(countries)))
I have a javascript object as follows.
{
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
}
I am trying to convert this object into an object given below.
{
name: "tom",
age: 5,
apple: 4,
orange: 13,
banana: 3
}
How do I achieve this? I have tried to loop through the fruits array but I am unable to find a way to create a variable with the fruit name and assign the qty to it.
You can use forEach and delete to clean up the old key. Take care not to overwrite keys accidentally, though (you could test if (e.name in obj) as a safety check).
const obj = {
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
};
obj.fruits.forEach(e => obj[e.name] = e.qty);
delete obj.fruits;
console.log(obj);
you can use below simple code
var b={
name: "tom",
age: 5}
for (var i = 0; i<a.fruits.length; i++) {
b[a.fruits[i].name]=a.fruits[i].qty;
}
This a generic function to convert if you don't want to mutate the original object. Destructure the object to get fruits and rest of the properties separately. Then you can use Object.assign() and map to to create a new object.
let obj = {
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
}
const converter = ({ fruits, ...rest }) =>
Object.assign(rest, ...fruits.map(({ name, qty }) => ({ [name]: qty })))
console.log(converter(obj))