1

Im trying to make sure I dont have this object in the array before adding it. If it is inside I want to remove it and add the new one at the top (very similar to a browser history)

    let numberArray =  [ {
  "name": "Smith",
    "number": "088-002-0002",
},
 {
  "name": "Jhon",
    "number": "088-111-2222",
},];

let test = { "name": "Smith",
  "number": "088-002-0002",};

numberArray.filter(obj => obj.number !== test.number);
numberArray.unshift(test);

console.log(numberArray);

//Expected
 Array [
 Object {
    "name": "Smith",
    "number": "088-002-0002",
 },
 Object {
   "name": "Jhon",
   "number": "088-111-2222",
 },
]
3
  • Are you going to use this operation a lot or very few times? Commented Feb 25, 2019 at 23:36
  • @molamk yes 10-15 max Commented Feb 25, 2019 at 23:40
  • The answers below are perfect for that Commented Feb 25, 2019 at 23:42

3 Answers 3

1

Use the function findIndex and then check if the indexOf > -1, in that case, remove that index, and finally unshift the new object.

// This is to illustrate -> "name": "Smithhhhh"
let numberArray = [{    "name": "Smithhhhh",    "number": "088-002-0002",  },  {    "name": "Jhon",    "number": "088-111-2222",  }],
    test = {  "name": "Smith",  "number": "088-002-0002",},
    indexOf = numberArray.findIndex(obj => obj.number === test.number);
    
if (indexOf !== -1) numberArray.splice(indexOf, 1);

numberArray.unshift(test);
console.log(numberArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

You can use includes and indexOf with unshift like so:

function addToArray(obj, arr) {
    if (arr.includes(obj)) {
        arr.splice(arr.indexOf(obj), 1);
        arr.unshift(obj);
    }
}

6 Comments

indexOf and includes?, this is comparing different references in memory.
@Ele what do you mean?
let obj1 = {name: "Ele"}; let obj2 = {name: "Ele"} -> obj1 === obj2 // returns false
The function includes compares each object vs the object you're passing as param. So, is comparing references in memory and not the keys, values within it.
How should I do it then?
|
0

Search for the object using .find(). If an object is not returned, use .unshift() to update the array.

let numberArray = [{
    "name": "Smith",
    "number": "088-002-0002",
  },
  {
    "name": "Jhon",
    "number": "088-111-2222",
  },
];

let test = {
  "name": "Smith",
  "number": "088-002-0002",
};



if (!numberArray.find(o => o.number === test.number)) {
  numberArray.unshift(test);
}



console.log(numberArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.