jquery move an item in object from one position to another - javascript

I got and object of objects like this:
var obj = {
0:{id: 1, name: 'one'},
1:{id: 2, name: 'two'},
2:{id: 3, name: 'three'},
3:{id: 4, name: 'four'}
};
I need to move an item under the key 1 from its current position to position 4 (where an item with id: 4 is), so it should look like the following:
var obj = {
0:{id: 1, name: 'one'},
1:{id: 3, name: 'three'},
2:{id: 4, name: 'four'},
3:{id: 2, name: 'two'},
};
The problem is that it is an object of objects, not an array. If it were an array I could do it with the help of the following function:
function array_move(arr, old_index, new_index) {
if (new_index >= arr.length) {
var k = new_index - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
};
But in this case I get the following error:
Uncaught TypeError: arr.splice is not a function
Any ideas how to fix it would be welcome. Thank you.

Create an array of keys and values and then order them:
var keys = Object.keys(obj);
var values = Object.values(obj);
var newObj = {};
values = array_move(values);
keys.forEach(function(el, i){
newObj[el] = values[i];
});

Related

merge array with unique keys

I have array of objects called newArray and oldArray.
Like this : [{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}]
example :
newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
]
oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
]
result will be = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]},
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]}
];
I wanted to merge both the array in such a way that whenever name and label are equal in both the arrays it should only consider newArray value.
I have tried
function mergeArrayWithLatestData (newData, oldData) {
let arr = [];
let i = 0; let j =0
while ((i < newData.length) && (j < oldData.length)) {
if ((findIndex(newData, { name: oldData[i].name, label: oldData[i].label })) !== -1) {
arr.push(newData[i])
} else {
arr.push(newData[i]);
arr.push(oldData[i]);
}
i += 1;
j += 1;
}
while (i < newData.length) {
arr.push(newData[i]);
}
return arr;
}
But i am not getting correct result.
Any suggestions?
You could add all array with a check if name/label pairs have been inserted before with a Set.
var newArray = [{ name: 'abc', label: 'abclabel', values: [1, 2, 3, 4, 5] }, { name: 'test', label: 'testlabel', values: [1, 2, 3, 4] }],
oldArray = [{ name: 'oldArray', label: 'oldArrayLabel', values: [1, 2, 3, 4, 5] }, { name: 'test', label: 'testlabel', values: [1, 2, 3, 4, 5] }],
result = [newArray, oldArray].reduce((s => (r, a) => {
a.forEach(o => {
var key = [o.name, o.label].join('|');
if (!s.has(key)) {
r.push(o);
s.add(key);
}
});
return r;
})(new Set), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can simply use Array.reduce() to create a map of the old Array and group by combination of name and label. Than iterate over all the elements or objects of the new Array and check if the map contains an entry with given key(combination of name and label), if it contains than simply update it values with the values of new array object, else add it to the map. Object.values() on the map will give you the desired result.
let newArray = [ {name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}, {name: 'test', label: 'testlabel', values: [1,2,3,4]} ];
let oldArray = [ {name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]}, {name: 'test', label: 'testlabel', values: [1,2,3,4,5]} ];
let map = oldArray.reduce((a,curr)=>{
a[curr.name +"_" + curr.label] = curr;
return a;
},{});
newArray.forEach((o)=> {
if(map[o.name +"_" + o.label])
map[o.name +"_" + o.label].values = o.values;
else
map[o.name +"_" + o.label] = o;
});
console.log(Object.values(map));
In your first while loop
while ((i < newData.length) && (j < oldData.length)) {
if ((findIndex(newData, { name: oldData[i].name, label: oldData[i].label })) !== -1)
{
arr.push(newData[i])
} else {
arr.push(newData[i]);
arr.push(oldData[i]);
}
i += 1;
j += 1;
}
i and j always have the same value, you are only comparing entries at the same positions in the arrays. If they have different lengths, you stop comparing after the shorter array ends. Your second while-loop will only be executed if newArray is larger than oldArray.
One possible solution is to copy the oldArray, then iterate over newArray and check if the same value exists.
function mergeArrayWithLatestData (newData, oldData) {
let arr = oldData;
for(let i = 0; i < newData.length; i++) {
let exists = false;
for(let j = 0; j < oldData.length; j++) {
if(newData[i].name === oldData[j].name && newData[i].label === oldData[j].label) {
exists = true;
arr[j] = newData[i];
}
}
if(!exists) {
arr.push(newData[i]);
}
}
return arr;
}
var newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
]
var oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
]
console.log(mergeArrayWithLatestData(newArray, oldArray));
You make copies of the original arrays, and in the first one, or change the element, or add:
function mergeArrayWithLatestData (a1, a2) {
var out = JSON.parse(JSON.stringify(a1))
var a2copy = JSON.parse(JSON.stringify(a2))
a2copy.forEach(function(ae) {
var i = out.findIndex(function(e) {
return ae.name === e.name && ae.label === e.label
})
if (i!== -1) {
out[i] = ae
} else {
out.push(ae)
}
})
return out
}
[ https://jsfiddle.net/yps8uvf3/ ]
This is Using a classic filter() and comparing the name/label storing the different pairs using just +. Using destructuring assignment we merge the two arrays keeping the newest first, so when we check the different the newest is always the remaining.
var newArray = [{ name: "abc", label: "abclabel", values: [1, 2, 3, 4, 5] },{ name: "test", label: "testlabel", values: [1, 2, 3, 4] }];
var oldArray = [{ name: "oldArray", label: "oldArrayLabel", values: [1, 2, 3, 4, 5] },{ name: "test", label: "testlabel", values: [1, 2, 3, 4, 5] }];
var diff = [];
oldArray = [...newArray, ...oldArray].filter(e => {
if (diff.indexOf(e.name + e.label) == -1) {
diff.push(e.name + e.label);
return true;
} else {
return false; //<--already exist in new Array (the newest)
}
});
console.log(oldArray);
Create an object, with key as name and label. Now, first add all the oldData records to the object and then add newData records in object. If there are any objects in common with same name and label, it will overwrite the old Data value. Finally, get the values of the Object which is the merged data set.
var arr1 = [{name: 'def', label: 'abclabel', values: [6,7]}, {name: 'abc', label: 'abclabel', values: [1,2,3,4,5]}];
var arr2 = [{name: 'xy', label: 'abclabel', values: [6,7]}, {name: 'abc', label: 'abclabel', values: [6,7]}];
function mergeArrayWithLatestData(newData, oldData) {
var result = {};
[...oldData, ...newData].forEach(o => result[o.name + "~~$$^^" + o.label] = o);
return Object.values(result);
}
let result = mergeArrayWithLatestData(arr1, arr2);
console.log(result);
Alternative: using a Map as the initial value in a reducer. You should know that (as in the selected answer) you loose information here, because you're not comparing on the values property within the array elements. So one of the objects with name/label pair test/testlabel will be lost in the merged Array. If concatenation in the snippet was the other way around (so newArray.concat(oldArray), the test/testLabel Object within the merged Array would contain another values property value.
const newArray = [
{name: 'abc', label: 'abclabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4]}
];
const oldArray = [
{name: 'oldArray', label: 'oldArrayLabel', values: [1,2,3,4,5]},
{name: 'test', label: 'testlabel', values: [1,2,3,4,5]}
];
const merged = [
...oldArray.concat(newArray)
.reduce( (map, value) =>
map.set(`${value.name}${value.label}`, value),
new Map())
.values()
];
console.log(merged);
function mergeArray(newArray, oldArray) {
var tempArray = newArray;
oldArray.forEach(oldData => {
var isExist = tempArray.findIndex(function (newData) {
return oldData.name === newData.name;
});
if (isExist == -1) {
tempArray.push(oldData);
}
});
return tempArray;
}
var newArray = [{
name: 'abc',
label: 'abclabel',
values: [1, 2, 3, 4, 5]
}, {
name: 'test',
label: 'testlabel',
values: [1, 2, 3, 4]
}];
var oldArray = [{
name: 'oldArray',
label: 'oldArrayLabel',
values: [1, 2, 3, 4, 5]
}, {
name: 'test',
label: 'testlabel',
values: [1, 2, 3, 4, 5]
}];
var resultArray = [];
resultArray = mergeArray(newArray, oldArray);
console.log(resultArray);

How can I return the property values of a nested JavaScript array nested in an object from JSON?

Given a JS array containing many objects which all contain arrays:
var data = [
{id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}]},
{id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]},
{id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];
How do I efficiently extract the inner most array (pages) values into an array?
var dataArray = [
{url: "www.abc.com", title: "abc"},
{url: "www.123.com", title: "123"},
{url: "www.xyz.com", title: "xyz"}
]
The easiest way to do this is to use Array#map like so:
var dataArray = data.map(function(o){return o.pages});
If pages is an array of objects (not a single object), this will result in an array of arrays, which you will need to flatten out for example using Array#reduce:
dataArray = dataArray.reduce(function(a,b){return a.concat(b)}, []);
You are looking for a flatMap
var data = [
{id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}]},
{id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]},
{id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];
const concat = (xs, ys) => xs.concat(ys);
const prop = x => y => y[x];
const flatMap = (f, xs) => xs.map(f).reduce(concat, []);
console.log(
flatMap(prop('pages'), data)
);
If by "efficiently" you actually mean "concisely", then
[].concat(...data.map(elt => elt.pages))
The data.map will result in an array of pages arrays. The [].concat(... then passes all the pages arrays as parameters to concat, which will combine all of their elements into a single array.
If you are programming in ES5, the equivalent would be
Array.prototype.concat.apply([], data.map(function(elt) { return elt.pages; }))
Here's a working example on how to achieve what you want:
var data = [
{id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}, {url:"www.google.com", title: "Google"}]},
{id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]},
{id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];
var arr = Array();
var arr2 = Array();
// You can either iterate it like this:
for (var i = 0; i < data.length; i++) {
// If you only want the first page in your result, do:
// arr.push(data[i].pages[0]);
// If you want all pages in your result, you can iterate the pages too:
for (var a = 0; a < data[i].pages.length; a++) {
arr.push(data[i].pages[a]);
}
}
// Or use the array map method as suggested dtkaias
// (careful: will only work on arrays, not objects!)
//arr2 = data.map(function (o) { return o.pages[0]; });
// Or, for all pages in the array:
arr2 = [].concat(...data.map(function (o) { return o.pages; }));
console.log(arr);
console.log(arr2);
// Returns 2x [Object { url="www.abc.com", title="abc"}, Object { url="www.123.com", title="123"}, Object { url="www.xyz.com", title="xyz"}]
use array map() & reduce() method :
var data = [
{id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}]},
{id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]},
{id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];
var dataArray = data.map(function(item) {
return item.pages;
});
dataArray = dataArray.reduce(function(a,b) {
return a.concat(b);
}, []);
console.log(dataArray);

Lodash object by Index

In lodash, how can I get an object from an array by the index at which it occurs, instead of searching for a key value.
var tv = [{id:1},{id:2}]
var data = //Desired result needs to be {id:2}
Let's take for example this collection:
var collection = [{id: 1, name: "Lorem"}, {id: 2, name: "Ipsum"}];
I will talk about two approaches, indexing and not indexing.
In general, indexing is better if you want to access many of the items, because you loop the collection once. If not, Meeseeks solution with find is the right choice.
Indexing
var byId = _.groupBy(collection, 'id');
var byName = _.groupBy(collection, 'name');
now you can reach each item by it indexed key:
console.log(byId[2]); // Object {id: 2, name: "Ipsum"}
console.log(byName.Lorem); // Object {id: 1, name: "Lorem"}
Without indexing
var item = _.find(collection, {id: 2});
console.log(item); // Object {id: 2, name: "Ipsum"}
I think what you're looking for is find
You can give it an object and it will return the matched element or undefined
Example
var arr = [ { id: 1, name: "Hello" }, { id: 2, name: "World" } ];
var data = _.find(arr, { id: 1 }); // => Object {id: 1, name: "Hello"}
var data = _.find(arr, { id: 3 }); // => undefined

Find and update an object in an array

I want to get an object from an array of objects, then update it.
var myObjs = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];
var myObjectToUpdate = _.findWhere(myObjs, { id: 2 });
myObjectToUpdate = { id: 2, name: "boop" };
myObjs[1] // { id: 2, name: "boop" }
Currently when I update myObject in the 3rd line, it does not update the array of objects. I'm assuming it is updating the new variable instead of referencing.
What is the correct way to do this?
#E_net4 is correct, you are reassigning the object you just found.
If all you need to do is update the name, try this:
var myObjs = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];
var myObjectToUpdate = _.findWhere(myObjs, { id: 2 });
myObjectToUpdate.name = "boop";
myObjs[1] // { id: 2, name: "boop" }
I guess this is what you want. You have, in your code, misconceptions. Please read my code and compare both.
Hope it helps!
function fn(arr, toReplace, newValue) {
for(var x in arr) {
for(var k in toReplace) {
if(arr[x][k] == toReplace[k]) {
arr[x] = newValue;
}
}
}
return arr;
};
var arr = [{ id: 1, name: "foo"}, { id: 2, name: "bar" }];
var newValue = {id: 2, name: "boop"};
arr = fn(arr, {id: 2}, newValue);
console.log(arr);

How to remove the same object in two arrays with lodash or underscore?

Now I have two object arrays,
var arr1 = [{id: 0, name: 'Jack'}, {id: 1, name: 'Ben'}, {id: 2, name: 'Leon'}, {id: 3, name: 'Gavin'}];
var arr2 = [{id: 0, name: 'Jack'}, {id: 5, name: 'Jet'}, {id: 2, name: 'Leon'}];
I want to remove those objects of same id in arr1 and arr2, so the results are:
var arr1 = [{id: 1, name: 'Ben'}, {id: 3, name: 'Gavin'}];
var arr2 = [{id: 5, name: 'Jet'}];
How to implement it with lodash or underscore?
Here are my implementation.
arr1_ids = _.pluck(arr1, 'id');
arr2_ids = _.pluck(arr2, 'id');
same_ids = _.intersection(arr1_ids, arr2_ids);
arr1 = _.remove(arr1, function(e) { return !_.contains(same_ids, e.id); });
arr2 = _.remove(arr2, function(e) { return !_.contains(same_ids, e.id); });
Is there any better way to do that?
Can you use _.difference?
same_elements = _.intersection(arr1, arr2);
arr1 = _.difference(arr1, same_elements);
arr2 = _.difference(arr2, same_elements);
I'm not sure how this should be done with underscore or lodash, but here's a JavaScript implementation.
It creates a filter function that you can then apply to both arrays to only keep the elements that aren't part of the intersection.
var arr1 = [{id: 0, name: 'Jack'}, {id: 1, name: 'Ben'}, {id: 2, name: 'Leon'}, {id: 3, name: 'Gavin'}];
var arr2 = [{id: 0, name: 'Jack'}, {id: 5, name: 'Jet'}, {id: 2, name: 'Leon'}];
var negative_intersection_filter = function(a, b) {
// create a map to speed up the filtering later
var map = a.reduce(function(map, current) {
// perform the intersection
map[current.id] = b.some(function(item) {
return item.id == current.id;
});
return map;
}, {});
// our filtering function, simple
return function(item) {
return !map[item.id];
}
}(arr1, arr2);
// apply the filter here
arr1 = arr1.filter(negative_intersection_filter);
arr2 = arr2.filter(negative_intersection_filter);
console.log(arr1);
console.log(arr2);
I think your algorithm is about right, here's a slightly different approach in plain js. I've used a, b instead of arr1, arr2 for brevity:
// Collect ids and sort
var ids = a.map(function(obj) {return obj.id}).concat(b.map(function(obj) {return obj.id})).sort();
// Get IDs that aren't duplicates
var nonDups = ids.filter(function(v, i, o){return v !== o[i-1] && v !== o[i+1]});
// Keep only the non-duplicates in each array
a.reduceRight(function(pre, cur, i, o){if (nonDups.indexOf(cur.id) == -1) o.splice(i, 1)},0);
b.reduceRight(function(pre, cur, i, o){if (nonDups.indexOf(cur.id) == -1) o.splice(i, 1)},0);
JSON.stringify(a) // [{"id":1,"name":"Ben"},{"id":3,"name":"Gavin"}]
JSON.stringify(b) // [{"id":5,"name":"Jet"}]
reduceRight is just used to iterate over each array backwards so that splicing doesn't affect the iteration.

Categories