Move an element to the front of an array: Javascript [duplicate] - javascript

This question already has answers here:
Move an array element from one array position to another
(44 answers)
Closed 2 years ago.
I have an array of objects with this format
let arr = [ { name: "test1", id: 5}, { name: "test2", id: 6 } , { name: "test3", id: 8 } ]
Now I basically want to move the item with 6 to the front of the array by re-arranging so that result becomes
let result = [ { name: "test2", id: 6 } , { name: "test1", id: 5}, { name: "test3", id: 8 } ]
What I have tried
const found = arr.find((element) => {
return element.id === 6;
});
if (found) {
const [...arr, found] = arr;
return found;
} else {
return arr;
}

You can make use of Array.unshift and Array.splice.
let arr = [{name:"test1",id:5},{name:"test2",id:6},{name:"test3",id:8}]
const moveToFront = (data, matchingId) => {
//find the index of the element in the array
const index = data.findIndex(({id}) => id === matchingId);
if(index !== -1) {
//if the matching element is found,
const updatedData = [...data];
//then remove that element and use `unshift`
updatedData.unshift(...updatedData.splice(index, 1));
return updatedData;
}
//if the matching element is not found, then return the same array
return data;
}
console.log(moveToFront(arr, 6));
.as-console-wrapper {
max-height: 100% !important;
}

You could sort the array with the delta of the checks.
const
array = [{ name: "test1", id: 5 }, { name: "test2", id: 6 }, { name: "test3", id: 8 }];
array.sort((a, b) => (b.id === 6) - (a.id === 6));
console.log(array);

const array = [{ name: "test1", id: 5 }, { name: "test2", id: 6 }, { name: "test3", id: 8 }];
const sortedArray = array.sort((a, b) => (b.id === 6) - (a.id === 6)); console.log(sortedArray);
discusses an easy way to sort your JavaScript Array by the order of the index number for each item in the Array object. This can be helpful if you want to sort alphabetically and not need to create a new String Array with a function like String.sort().
A quick tip that can be useful to you if you want a quick solution to sorting an Array in JavaScript is below.Remember that it is always best practice to use the Array methods built into the language. They are created to work fast and efficient. However, if you really want to sort your array by index number and not have an array of strings, then this article will be for you.:
String→Number: When a function returns a Number value, then JavaScript interprets it as being equal to the Number value in the code...The function is used by passing two parameters, which should return true when they are equal and false when they are not equal.In this case, we are sort of reverse comparing them. We are checking the ID of the items inside the Array to see if they match, but we subtract one to check if they are less than. This is because when we call .sort(), JavaScript is sorting alphabetically and an ID with a value of 6 will be at the end of the list. So, a value of -1 will make it appear in the correct order.If you want to use this method for your Array, then please add a comment below!

You can use Array.unshift() to add element to the beginning of the array and Array.splice() to remove the array element.
let arr = [ { name: "test1", id: 5}, { name: "test2", id: 6 } , { name: "test3", id: 8 } ]
let result = [...arr];
const index = result.findIndex(e => e.id === 6)
result.unshift(result.splice(index, 1)[0])
console.log(result);

You can make use of filter and unshift
let arr = [{ name: "test1", id: 5 },{ name: "test2", id: 6 },{ name: "test3", id: 8 }];
let firstObject;
let result = arr.filter((value) => {
if (value.id != 6) return value;
firstObject = value;
});
result.unshift(firstObject);
console.log(result);

Related

Efficient way to get unique objects from array of objects, by object property?

Here is my array of objects
const array = [
{id: 1, data: "foo"},
{id: 1, data: "bar"},
{id: 2, data: "baz"}
]
I want to remove all duplicate objects by its id and return only the array of objects that have an unique id.
Expected result:
[
{id: 2, data: "baz"}
]
This is what I have now: O(n^2)
function getUnique(array) {
const newArray = []
for (let obj of array) {
if (array.filter(x => x.id === obj.id).length === 1) {
newArray.push(obj)
}
}
return newArray
}
Whats the more efficient way to achieve this?
Is it possible to get the time-complexity to O(n) or O(n log n)?
const array = [{
id: 1,
data: "foo"
},
{
id: 1,
data: "bar"
},
{
id: 2,
data: "baz"
}
]
let map = {};
array.forEach(x => {
map[x.id] = (map[x.id] || 0) + 1
});
console.log(array.filter(x => map[x.id] === 1))
I would suggest to count the number of occurrences in your array and store them in a Map. Next you filter all element, which count is 1
function getUnique(arr) {
const count = new Map();
arr.forEach((element) => {
count.set(element.id, (count.get(element.id) || 0) + 1);
});
return array.filter((element) => {
return count.get(element.id) === 1;
});
}
This has a runtime of 2(n) since you have to iterate over them twice

How to dedupe an array of objects by a key value pair?

// This is a large array of objects, e.g.:
let totalArray = [
{"id":"rec01dTDP9T4ZtHL4","fields":
{"user_id":170180717,"user_name":"abcdefg","event_id":516575,
}]
let uniqueArray = [];
let dupeArray = [];
let itemIndex = 0
totalArray.forEach(x => {
if(!uniqueArray.some(y => JSON.stringify(y) === JSON.stringify(x))){
uniqueArray.push(x)
} else(dupeArray.push(x))
})
node.warn(totalArray);
node.warn(uniqueArray);
node.warn(dupeArray);
return msg;
I need my code to identify duplicates in the array by a key value of user_id within the objects in the array. Right now, my code works to identify identical objects in the array, but I need it to identify dupes based on a key value inside the objects instead. How do I do this? I am struggling to figure out how to path the for each loop to identify the dupe based on the key value instead of the entire object.
Right now, my code works to identify identical objects in the array, but I need it to identify dupes based on a key value inside the objects instead. How do I do this?
Don’t compare the JSON representation of the whole objects then, but only their user_id property specifically.
totalArray.forEach(x => {
if(!uniqueArray.some(y => y.fields.user_id === x.fields.user_id)){
uniqueArray.push(x)
} else(dupeArray.push(x))
})
You could take a Set and push to either uniques or duplicates.
var array = [
{ id: 1, data: 0 },
{ id: 2, data: 1 },
{ id: 2, data: 2 },
{ id: 3, data: 3 },
{ id: 3, data: 4 },
{ id: 3, data: 5 },
],
uniques = [],
duplicates = [];
array.forEach(
(s => o => s.has(o.id) ? duplicates.push(o) : (s.add(o.id), uniques.push(o)))
(new Set)
);
console.log(uniques);
console.log(duplicates);
.as-console-wrapper { max-height: 100% !important; top: 0; }
One way is to keep a list of ids you found so far and act accordingly:
totalArray = [
{ id: 1, val: 10 },
{ id: 2, val: 20 },
{ id: 3, val: 30 },
{ id: 2, val: 15 },
{ id: 1, val: 50 }
]
const uniqueArray = []
const dupeArray = []
const ids = {}
totalArray.forEach( x => {
if (ids[x.id]) {
dupeArray.push(x)
} else {
uniqueArray.push(x)
ids[x.id] = true
}
})
for (const obj of uniqueArray) console.log("unique:",JSON.stringify(obj))
for (const obj of dupeArray) console.log("dupes: ",JSON.stringify(obj))

Check if an array of objects exists

I have an array of objects:
items: [
{ name: "Cheese Puffs", price: 3 },
{ name: "Can of Soda", price: 1.75 }
];
I want to do something like items["cheesePuffs"] === true. But as it is in an array it won't work properly.
What you want is Array.find().
myArrOfObjects.find(el => el.cheesePuffs);
Assuming the property you're looking for is truthy, this returns the element, {cheesePuffs: "yes"} which is truthy. If it weren't found, it would be undefined.
You can use some and hasOwnProperty, If you need actual value instead of Boolean values you can use find instead of some
const myArrOfObjects = [{
cheesePuffs: "yes"
},
{
time: "212"
}];
let findByName = (name) => {
return myArrOfObjects.some(obj=> {
return obj.hasOwnProperty(name)
})
}
console.log(findByName("cheesePuffs"))
console.log(findByName("time"))
console.log(findByName("123"))
okay simple solutions
try this
const x = [{}];
if(x.find(el => el.cheesePuffs) == undefined)
console.log("empty objects in array ")
const myArrOfObjects = [{
cheesePuffs: "yes"
},
{
time: "212"
}];
if(myArrOfObjects.find(el => el.cheesePuffs) == undefined)
console.log("empty objects in array ")
else
console.log("objects available in array ")
As suggestion, you can also decide to not use an array, but to use a json object, where the index of each item is the unique name of your objects (in the example "cheesePuffs" identifies "Cheese Puffs")
let items = {
"cheesePuffs": {name: "Cheese Puffs",price: 3},
"canOfSoda": {name: "Can of Soda",price: 1.75},
};
console.log("exist: ", items.cheesePuffs!== undefined)
console.log(items.cheesePuffs)
// can also access to item in this way:
console.log(items["cheesePuffs"])
console.log("not exist", items.noCheesePuffs!== undefined)
console.log(items.noCheesePuffs)
Try the following code. It will return you the object where name matches to 'Cheese Puffs'.
let items = [{
name: "Cheese Puffs",
price: 3
},
{
name: "Can of Soda",
price: 1.75
}
];
let itemExist = items.find(x => x.name === 'Cheese Puffs');
if (itemExist) {
console.log(itemExist);
} else {
console.log("Item not Exist");
}
You can use find
let exist = myArrOfObjects.find(o => o.cheesePuffs === 'yes')
First of all you have an array of objects so you can't simply use
myArrOfObjects["cheesePuffs"]
because array required an index so it should be myArrOfObjects[0]["cheesePuffs"]
let items = [
{ name: "Cheese Puffs", price: 3 },
{ name: "Can of Soda", price: 1.75 }
];
let filter = items.find( el => el.price === 3 );
console.log(filter);
another approach
let items = [
{ name: "Cheese Puffs", price: 3 },
{ name: "Can of Soda", price: 1.75 }
];
let filter = items.filter( el => el.price === 3 );
console.log(filter);

Return an array item that doesn't match any item in another array? [duplicate]

This question already has answers here:
How to get the difference between two arrays of objects in JavaScript
(22 answers)
check the difference between two arrays of objects in javascript [duplicate]
(3 answers)
Closed 3 years ago.
I have two identical arrays of objects.
I then add an object to one of the arrays at a random index:
Arr1 = [{ id: "a" }, { id: "b" }, { id: "c" }]
Arr2 = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }]
How would I go about comparing the two arrays, extracting that new object from Arr2 and assigning that object to a constant?
This is my best effort:
const newPlan
if (state.plans.length !== data.allPlansJson.edges.length) {
data.allPlansJson.edges.map(staticPlan => {
state.plans.map(planInState => {
planInState !== staticPlan && newPlan = staticPlan
})
})
}
Too add even more context:
I'm getting objects from the array data.allPlansJson.edges and spreading them in my a database collection. I'm then getting all of those objects and putting them back into an array in my redux state.
This function is to detect when there is a new object added to the data.allPlansJson.edges array and execute a redux action that posts this new object to my database collection.
For this specific scenario, in order to get just the new items you can filter out any points that are in the orignial.
const arrA = [{ id: "a" }, { id: "b" }, { id: "c" }];
const arrB = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }];
const newItems = arrB.filter(b => !arrA.some(a => a.id === b.id));
arrB.filter loops over arrB calling the arrow function. To keep an item we return true in this callback. To get rid of an item we return false.
arrA.some loops over arrA calling the provided arrow function. The function will resolve true if any of the items return true. Since we are matching for items found in the array we add the ! before arrA.some in order to find items not found
You can now grab the first item from newItems by doing
const [someConst] = newItems;
Note: this is a one-way search. If there are new ones in arrA they will not be found
You could find the object by checking the object with with the one at the same index.
var array1 = [{ id: "a" }, { id: "b" }, { id: "c" }],
array2 = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }],
inserted = array2.find((o, i) => o.id !== array1[i].id);
console.log(inserted);
Arr1 = [{ id: "a" }, { id: "b" }, { id: "c" }];
Arr2 = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }];
function findExtra(arr1, arr2) {
len1 = arr1.length;
len2 = arr2.length;
for (i = 0; i < Math.min(len1, len2); i++) {
if (arr1[i].id !== arr2[i].id) { // Compare elements pairwise
return len1 > len2 ? arr1[i] : arr2[i]; // Return the newly added one
}
}
// The new element is the last one
return len1 > len2 ? arr1[len1 - 1] : arr2[len2 - 1];
}
console.log(findExtra(Arr1, Arr2));
Is this what you are looking for?

Remove object from array knowing its id [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 7 years ago.
I have an array of objects:
var myArr;
Let’s say that on page load it contains 10 objects with the following structure:
{
Id: …,
Name: …
}
How can I remove an object from myArr by its Id?
Try like this
var id = 2;
var list = [{
Id: 1,
Name: 'a'
}, {
Id: 2,
Name: 'b'
}, {
Id: 3,
Name: 'c'
}];
var index = list.map(x => {
return x.Id;
}).indexOf(id);
list.splice(index, 1);
console.log(list);
JSFIDDLE
Or you can utilize .filter()
Like this
var id = 2;
var list = [{
Id: 1,
Name: 'a'
}, {
Id: 2,
Name: 'b'
}, {
Id: 3,
Name: 'c'
}];
var lists = list.filter(x => {
return x.Id != id;
})
console.log(lists);
DEMO
Two solutions, one evolve creating new instance and one changes the instance of your array.
Filter:
idToRemove = DESIRED_ID;
myArr = myArr.filter(function(item) {
return item.Id != idToRemove;
});
As you can see, the filter method returns new instance of the filtered array.
Second option is to find the index of the item and then remove it with splice:
idToRemove = DESIRED_ID;
index = myArr.map(function(item) {
return item.Id
}).indexOf(idToRemove);
myArr.splice(index, 1);
can you try
newArray = myArr
.filter(function(element) {
return element.id !== thisId;
});

Categories